反向打印链表(或反向填充?)
Linked list printing in reverse (or filling in reverse?)
如果我输入此代码为 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;
}
- 我意识到我不应该转换 malloc 的 return,而应该检查 scanf 的 return!这只是学习如何构建链表的测试代码。
你这里有内存泄漏
end = (List*)malloc(sizeof(List));
end = NULL;
你的第一个 start
迷路了。
在循环中为start
分配内存之前,您需要先将start
分配给end
。
start = (List*)malloc(sizeof(List));
end = NULL;
while(scanf("%d", &(start -> a )) == 1)
{
end = start;
start = (List*)malloc(sizeof(List));
start -> next = end;
}
我想补充一点,这实际上是 反向填充 link 列表。因为代码从头开始倒序填充link列表
您确实以最新条目位于列表开头的方式将数据输入到列表中。
解决此问题的一种方法是使 end
指向最后一个 指针 到 next
,并将其设置为指向 [=13] =] 开头。请注意 end
现在是 "double-pointer":
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;
}
如果我输入此代码为 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;
}
- 我意识到我不应该转换 malloc 的 return,而应该检查 scanf 的 return!这只是学习如何构建链表的测试代码。
你这里有内存泄漏
end = (List*)malloc(sizeof(List));
end = NULL;
你的第一个 start
迷路了。
在循环中为start
分配内存之前,您需要先将start
分配给end
。
start = (List*)malloc(sizeof(List));
end = NULL;
while(scanf("%d", &(start -> a )) == 1)
{
end = start;
start = (List*)malloc(sizeof(List));
start -> next = end;
}
我想补充一点,这实际上是 反向填充 link 列表。因为代码从头开始倒序填充link列表
您确实以最新条目位于列表开头的方式将数据输入到列表中。
解决此问题的一种方法是使 end
指向最后一个 指针 到 next
,并将其设置为指向 [=13] =] 开头。请注意 end
现在是 "double-pointer":
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;
}