我对数据结构太新了,实际上我昨天才开始。下面是代码:链接列表出现问题(添加和打印)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int x;
node *next;
};
void addToList(node *r, int a);
void printList(node *r);
int main()
{
node *root;
root = NULL;
for (int i = 0; i < 5; i++)
{
int a;
scanf("%d", &a);
addToList(root, a);
}
printList(root);
return 0;
}
void addToList(node *r, int a)
{
while (r != NULL)
r = r -> next;
r = (node *)malloc(sizeof(node));
r -> x = a;
r -> next = NULL;
}
void printList(node *r)
{
while (r != NULL)
{
printf("%d ", r -> x);
r = r -> next;
}
printf("\n");
}
我希望程序获取新的5元到列表中,然后打印它们。但该计划的结束没有发生。我的错是什么?
应该'空隙addToList(节点* R,INT A){ 而(!R->下一= NULL) R = R - >下; r-> next =(node *)malloc(sizeof(node)); r-> next-> x = a; r-> next-> next = NULL; }' – roottraveller
抱歉,但没有奏效。 – Atreidex
它定义了第一个元素后工作。我应该永远定义第一个元素吗?没有办法完全清空列表? – Atreidex