如果我输入此代码的输入为1 2 3 4 5
,则按Ctrl-D结束程序,它将打印
0 --> 5 --> 4 --> 3 --> 2 -->
,这很奇怪。我尝试按照建立链表的教程,但我认为我做错了。
#include <stdio.h>
#include <stdlib.h>
struct list
{
int a;
struct list *next;
};
typedef struct list List;
int main (void)
{
List *start, *end;
end = (List*)malloc(sizeof(List));
end = NULL;
while(scanf("%d", &(start -> a )) == 1)
{
start = (List*)malloc(sizeof(List));
start -> next = end;
end = start;
}
end = start;
while(start)
{
printf("%d --> ", start -> a);
start = start -> next;
}
return 0;
}
答案 0 :(得分:3)
此处有内存泄漏
end = (List*)malloc(sizeof(List));
end = NULL;
你的第一个start
迷路了。
在为循环中的start
分配内存之前,您需要将end
分配给start
。
start = (List*)malloc(sizeof(List));
end = NULL;
while(scanf("%d", &(start -> a )) == 1)
{
end = start;
start = (List*)malloc(sizeof(List));
start -> next = end;
}
我想补充一点,这实际上是反向填充链接列表。因为代码从头开始以相反的顺序填充链接列表
答案 1 :(得分:2)
您确实以最近条目最终位于列表首部的方式将数据输入列表。
解决此问题的一种方法是让end
指向next
的最后一个指针,并将其设置为在开头指向start
。请注意,end
现在是&#34;双指针&#34;:
List *start = NULL, **end = &start;
int a; // read data into a local, not into the node
while(scanf("%d", &a) == 1) {
// Make a new node
List *node = malloc(sizeof(List));
// set the data to what we just read
node->a = a;
// This is the last node, so next is NULL
node->next = NULL;
// end points to previous node's next, so add new node to it
*end = node;
// Finally, re-point end to new node's next
end = &node->next;
}