Linked List Demo
原始 C 程序
```{.c} #include <stdio.h> #include <stdlib.h> #include <string.h>
// … 这里粘贴完整的 Linkedlist.c 代码 … #include <stdio.h> #include <stdlib.h> #include <string.h>
typedef struct Node { char name[32]; struct Node *next; } Node;
/* 在链表尾部插入 name,返回“新的尾结点” / Node push_back(Node last, const char name) { Node p = (Node)malloc(sizeof(Node)); if (!p) { perror(“malloc”); exit(1); }
strncpy(p->name, name, sizeof(p->name)-1);
p->name[sizeof(p->name)-1] = '\0';
p->next = NULL;
if (last) { // 不是第一个节点:把它接在尾巴后
last->next = p;
}
return p; // 返回新的“尾结点”
}
/* 打印链表 / void print_list(Node head) { for (Node *cur = head; cur; cur = cur->next) { printf(“%s%s”, cur->name, cur->next ? ” -> ” : ” -> null“); } }
/* 统计节点数 / int count(Node h) { int numberofnodes = 0; for (Node *p = h; p != NULL; p = p->next) { numberofnodes++; } return numberofnodes; }
int main(void) { Node head = NULL; Node tail = NULL;
// 构造图里的初始链表:Jacob -> Joseph -> Mary
tail = push_back(NULL, "Jacob"); // 第一个节点
head = tail; // 记录头指针
tail = push_back(tail, "Joseph"); // 接在尾部
tail = push_back(tail, "Mary");
print_list(head);
printf("This linked list has %d nodes.\n\n", count(head));
// 在末尾插入 Ann(对应 Fig. 3.6 第二行)
tail = push_back(tail, "Ann");
print_list(head);
printf("This linked list has %d nodes.\n", count(head));
return 0;
}