gpt4 book ai didi

c - 使用链表分隔偶数和奇数的函数

转载 作者:行者123 更新时间:2023-11-30 14:40:32 26 4
gpt4 key购买 nike

我正在尝试从用户那里获取一个数字并创建2个链接列表,一个仅包含偶数,另一个包含奇数,我必须返回已插入的总数,并通过引用传递链表。我的主要问题是返回两个新的链表,这是我到目前为止所做的。我收到一个错误错误 C2440“函数”:无法从“节点 **”转换为“节点”。

    #include <stdio.h>
#include <stdlib.h>

typedef struct node{
int data;
struct node *next;
}node;

struct node* head;
int get_values(node,node);

void main() {
node *even_node,*odd_node;
get_values(&even_node,&odd_node);

}
int get_values(node *even, node *odd) {
int value, counter_total = 0;
node *curr_even;
node *curr_odd;
head = NULL;
printf("enter value:");
scanf_s("%d", &value);
if (value == -1) {
return NULL;
}
if (value % 2 == 0) {
even = (node*)malloc(sizeof(node));
curr_even = even;
even->data = value;
counter_total++;
}
else {
odd = (node*)malloc(sizeof(node));
curr_odd = odd;
odd->data = value;
counter_total++;
}
//2nd and on insertion.
while (value != -1) {
printf("enter a value positive value");
scanf_s("%d", &value);
if (value == -1) {
curr_even->next = NULL;
curr_odd->next = NULL;
break;
}

else if (value % 2 == 0) {
curr_even->next = (node *)malloc(sizeof(node));
curr_even = curr_even->next;
curr_even->data = value;//current value
counter_total++;
}
else {
curr_odd->next = (node*)malloc(sizeof(node));
curr_odd = curr_odd->next;
curr_odd->data = value; //current value
counter_total++;
}

return counter_total;
}
}

最佳答案

您的代码有很多问题。

  1. getvalues 的函数定义应该有一个双指针。
  2. 在函数中,您正在对函数参数进行malloc。而您需要 malloc 一个局部变量并将其添加到列表中。
  3. 当单个 do while 循环就足够时,您会添加不必要的重复代码。

请参阅下面的固定代码

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
int data;
struct node *next;
}node;

struct node* head;
int get_values(node **,node **);

void main() {
node *even_node= NULL,*odd_node= NULL;
get_values(&even_node,&odd_node);

}
int get_values(node **even, node **odd) {
int value, counter_total = 0;
node *curr_even;
node *curr_odd;
node *new_node;

do
{
printf("enter value:");
scanf("%d", &value);
if (value == -1) {
return counter_total;
}
if (value % 2 == 0)
{
new_node = (node*)malloc(sizeof(node));
new_node -> data = value;
new_node -> next = NULL;
if (*even == NULL)
{
*even = new_node;
curr_even = *even;
}
else
{
curr_even ->next = new_node;
curr_even = curr_even -> next;
}
counter_total++;
}
else
{
new_node = (node*)malloc(sizeof(node));
new_node -> data = value;
new_node -> next = NULL;

if (*even == NULL)
{
*even = new_node;
curr_even = *even;
}
else
{
curr_even ->next = new_node;
curr_even = curr_even -> next;
}
counter_total++;
}
}while (1);
}

关于c - 使用链表分隔偶数和奇数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55514121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com