爲了學習,我正在編寫一個簡單的鏈表實現。我的鏈表包含node
結構,其中包含一個int
值和一個指向下一個節點的指針。當我運行我的代碼時,它會無休止地循環,即使它在到達空指針時應該終止。我究竟做錯了什麼?鏈接列表循環不休
#include <stdio.h>
struct node {
int value;
struct node *next_node;
};
struct node * add_node(struct node *parent, int value)
{
struct node child;
child.value = value;
child.next_node = NULL;
parent->next_node = &child;
return parent->next_node;
}
void print_all(struct node *root)
{
struct node *current = root;
while (current != NULL) {
printf("%d\n", current->value);
sleep(1);
current = current->next_node;
}
}
int main()
{
struct node root;
root.value = 3;
struct node *one;
one = add_node(&root, 5);
print_all(&root);
}
你在調試器中經過了多久? – kfsone