我想了解链接列表的代码。我明白他们是如何工作的。 我在看一些代码做动态内存和链表,我在这里简单的:C - 链接列表
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char *word;
struct node *next;
} node;
void display_word(node *start) {
node *start_node = start;
puts("");
for(; start_node != NULL; start_node = start_node->next) {
printf("%s", start_node->word);
}
}
node* create_node(char *input) {
node *n = malloc(sizeof(node));;
n->word = strdup(input);
n->next = NULL;
return n;
}
int main() {
node *start_node = NULL;
node *n = NULL;
node *next_node = NULL;
char word_holder[20];
for(; fgets(word_holder,80,stdin) != NULL; n = next_node) {
next_node = create_node(word_holder);
if(start_node == NULL)
start_node = next_node;
if(n != NULL)
n->next = next_node;
}
display_word(start);
}
所以程序创建用户输入每个字的链接列表,然后将其打印出来。 我不明白的是在main()函数中,每次将next_node分配给新节点以创建新节点,但start_node指向next_node,因此它会指向next_node每次创建的每个新节点?那么如何保持清单呢?我们每次都不应该失去旧节点吗?
有人可以解释一下。
OFF TOPIC:你的名字是“miniJavaLearner”,你在C编码?呵呵 :) –