【发布时间】:2017-11-28 22:26:32
【问题描述】:
这是实现单链表的尝试。
问题是当尝试使用while (traverse != NULL) 打印列表时,程序输出1,第一个节点的数据,但不打印所有其他节点的数据。我是否错误地链接了节点,如果是,在哪里?
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
struct node *root;
int main(void) {
Node *list, *traverse;
/* root will always be the first of the list */
root = malloc(sizeof(*list));
list = root;
list->data = 1;
list->next = NULL;
list = list->next;
list = malloc(sizeof(*list));
list->data = 2;
list->next = NULL;
list = list->next;
list = malloc(sizeof(*list));
list->data = 3;
list->next = NULL;
list = list->next;
list = malloc(sizeof(*list));
list->data = 4;
list->next = NULL;
list = list->next;
list = malloc(sizeof(*list));
list->data = 5;
list->next = NULL;
list = list->next;
traverse = root;
while (traverse != NULL) {
printf("%d\n", traverse->data);
traverse = traverse->next;
}
return 0;
}
输出:
$ gcc main.c && ./a.out
1
预期输出:
$ gcc main.c && ./a.out
1
2
3
4
5
更新:
正如大家所建议的那样,我已经更新了我的源文件:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
struct node *root;
int main(void) {
Node *list, *traverse;
/* root will always be the first of the list */
root = malloc(sizeof(*list));
list = root;
list->data = 1;
list->next = malloc(sizeof(*list));
list = list->next;
list->data = 2;
list->next = malloc(sizeof(*list));
list = list->next;
list->data = 3;
list->next = malloc(sizeof(*list));
list = list->next;
list->data = 4;
list->next = malloc(sizeof(*list));
list = list->next;
list->data = 5;
list->next = NULL;
traverse = root;
while (traverse != NULL) {
printf("%d\n", traverse->data);
traverse = traverse->next;
}
return 0;
}
非常感谢大家!
【问题讨论】:
标签: c linked-list singly-linked-list