【发布时间】:2015-12-18 22:44:40
【问题描述】:
所以,最近我不得不创建一个链表结构,我认为有一个创建它的功能(希望如此),但现在我遇到了将它打印到控制台这样简单的问题。我不知道我创建的结构是否有问题,或者我的打印有问题。如果有人能发现我的代码有什么问题,我将不胜感激:
struct z { int a; struct z *next; };
struct z *head, *node, *next;
int data, x = 1;
int CreateList() {
printf("Enter 0 to end\n");
printf("Enter data no. %d: ", x);
x++;
scanf("%d", &data);
if (data == 0) return 0;
head = (struct z *)malloc(sizeof(struct z));
if (head == NULL) { printf("Error creating head"); return 0; }
node = head;
node->a = data;
node->next = NULL;
while (data) {
next = (struct z *)malloc(sizeof(struct z));
if (next == NULL) { printf("Error creating next node no. %d", x); return 0;}
node = next;
printf("Enter data no. %d: ", x);
x++;
scanf("%d", &data);
node->a = data;
node->next = NULL;
}
return 0;
}
int main() {
CreateList();
node = head;
while (node != NULL) {
printf("%d ", node->a);
node = node->next; //<=== crash on this line
}
return 0;
}
我的输出始终只是第一个输入的 int,然后它在标记的行上全部崩溃。
【问题讨论】:
-
输入、输出和预期输出是什么?
-
node=next;-->node->next=next; node=next;也许还有其他事情 很大程度上取决于输入 - 未发布。 -
函数收集 int 数据片段,将它们放入“a”变量并保存到节点,然后创建新的,并重复。我想要的输出是按照放入链表的顺序打印出来的所有数据片段。
-
发布输入比描述输入更有用。
-
不要将
malloc和朋友的结果投射到C中。