1 #include <stdio.h>
2 #include <stdlib.h>
3 /*
4 尾插法创建链表:尾插法就是每次都把结点插在尾结点后面
5 总结:尾插法相对头插法 需要多定义一个指针pt来保存尾结点的地址。
6 */
7 typedef struct node
8 {
9 int data;
10 struct node * next;
11 }NODE;
12 NODE * createList()
13 {
14 NODE *head = (NODE *)malloc(sizeof(NODE));
15 head->next = NULL;
16
17 NODE * cur = NULL;
18 NODE * pt = head;//pt保存尾结点的地址,即:pt指向尾结点。
19 int data;
20 printf("请输入结点的数据\n");
21 scanf("%d",&data);
22
23 while(data)
24 {
25 cur = (NODE *)malloc(sizeof(NODE));
26 cur->data = data;
27 pt->next = cur;
28 cur->next = NULL;
29 pt = cur; //pt指向尾结点
30 scanf("%d",&data);
31 }
32 return head;
33 }
34 void traverList(NODE * head)
35 {
36 head = head->next;
37 while(head)
38 {
39 printf("%d",head->data);
40 head = head->next;
41 }
42 }
43 int main(void)
44 {
45 //建立链表
46 NODE * head = createList();
47 //遍历并输出链表
48 traverList(head);
49
50 return 0;
51 }