1 /*建立一个整数链表*/
2 #include <stdio.h>
3 #include <stdlib.h>
4 struct chain
5 {
6 int value;
7 struct chain *next;
8 };
9 struct chain *create()
10 {
11 struct chain *head, *tail, *p;
12 int x;
13 head = tail = NULL;
14 printf("Input data.\n");
15 while (scanf("%d", &x) == 1) /*如果输入的是一个整型的数据,那么向下执行*/
16 {
17 p = (struct chain *)malloc(sizeof (struct chain));
18 /*首先为要新创建的表元p开辟一个内存空间*/
19 p->value = x;
20 p->next = NULL;
21 if (head == NULL)
22 head = tail = p;
23 else
24 /*tail为倒数第二个表元指针,tail->始终指向最后一个表元*/
25 tail = tail->next;
26 tail->next = p;
27 }
28 return head;
29 }
30
31 int main(){
32 struct chain *p, *q;
33 q = create();
34 while (q) {
35 printf("%d\n", q->value);
36 p = q->next;
37 free(q);
38 q = p;
39 }
40 getchar();
41 return 0;
42 }