cla*_*ntl 3 c struct linked-list while-loop
我对 C 相当陌生,但我的老师要求我实现一个链表。
当我在 Repl.it 中运行下面的代码时,它可以工作,但是当我在我的机器上使用 Windows 上的 gcc 运行它时,它不会退出 while 循环。
有任何想法吗?
#include <stdio.h>
#include <stdlib.h>
struct node *newNode(int);
void llAppend(int);
void llPrint(void);
struct node {
int data;
struct node *next;
};
struct node *ll;
int main(void) {
llAppend(2);
llAppend(3);
llPrint();
}
struct node *newNode(int data) {
struct node *tmp;
tmp = malloc(sizeof (struct node));
tmp->data = data;
return tmp;
}
void llAppend(int data) {
struct node *tmp;
if (ll == NULL) {
ll = newNode(data);
return;
}
tmp = ll;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = newNode(data);
}
void llPrint(void) {
struct node *tmp;
tmp = ll;
while (tmp != NULL) {
printf("%d\n", tmp->data);
tmp = tmp->next;
}
}
Run Code Online (Sandbox Code Playgroud)
它不会退出 while 循环。有任何想法吗?
问题是你没有tmp->next在newNode(). 因此,在while循环中,您的代码在尝试检查tmp->next.
当我在 Repl.it 中运行解决方案时,它完全正常。
它很不走运。当您访问未初始化的内存时,不知道会发生什么。有可能tmp->next碰巧NULL代码在这种情况下工作。
你需要设置tmp->next到NULL在newNode()这样的:
tmp->next = NULL;
Run Code Online (Sandbox Code Playgroud)
此外,始终检查 的返回值malloc,以确保它不是NULL。
struct node *newNode(int data) {
struct node *tmp;
tmp = malloc(sizeof (struct node));
if (tmp == NULL) {
exit(EXIT_FAILURE);
}
tmp->data = data;
tmp->next = NULL;
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
此外,请考虑使用valgrind和gdb,它们是可以帮助您调试此类问题的强大工具。
旁注:你的main函数缺少一个return语句——添加return EXIT_SUCCESS;