我正在尝试,从用户那里得到一个号码并创建2个链表,一个只有偶数,另一个有奇数,我必须返回已插入的总数,并通过引用传递链接 - 名单。我的主要问题是返回2个新的链表,这是我到目前为止所做的。我收到错误错误C2440'功能':无法从'node **'转换为'node'。
#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;
}
}
你的代码有很多问题。
getvalues
的函数定义应该有一个双指针。malloc
。虽然您需要malloc一个局部变量并将其添加到列表中。请参阅下面的固定代码
#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);
}
如果您希望通过引用传递,可以按照以下方式进行操作。
int get_values(node **even, node **odd) {
int value, counter_total = 0;
printf("enter value:");
scanf_s("%d", &value);
while (value != -1) {
if (value % 2 == 0) {
while(*even != NULL) even= &(*even)->next; //Move the pointer till last node.
*even = (node *)malloc(sizeof(node));
(*even)->data = value;//current value
(*even)->next = NULL;
counter_total++;
}
else {
while(*odd != NULL) odd= &(*odd)->next;
*odd = (node *)malloc(sizeof(node));
(*odd)->data = value;//current value
(*odd)->next = NULL;
counter_total++;
}
printf("enter a value positive value");
scanf_s("%d", &value);
}
return counter_total;
}