1 #include <stdio.h>
2 #include <stdlib.h>
3 typedef struct node * Node; /* 定一个struct node类型的指针,struct node *就等同于Node */
4 Node head; /* 链表头 */
5 /* 链表结点结构
6 * val :结点的值
7 * next :下一个结点的指针
8 */
9 struct node{
10 int val;
11 Node next;
12 };
13 /* 插入结点函数 */
14 int insert(int val)
15 {
16 Node p, q;
17 p = head;
18 if(p != NULL){ /* 寻找适当的插入位置 */
19 while(p->next != NULL){
20 p = p->next;
21 }
22 }
23 q = (Node)malloc(sizeof(struct node)); /* 创建一个新的结点 */
24 if(q == NULL)
25 return -1;
26 q->next = NULL; /* 对新结点进行赋值 */
27 q->val = val;
28 if(p == NULL){ /* 空链表 */
29 head = q;
30 return 1;
31 }
32 p->next = q; /* 新结点插入到链表中 */
33 return 1;
34 }
35 void print()
36 {
37 Node p = head;
38 while(p != NULL){ /* 输出每个结点的值 */
39 printf("%d\n", p->val);
40 p = p->next;
41 }
42 }
43 /* 遍历链表,释放每一个结点 */
44 void destroy()
45 {
46 Node p = head; /* 从链表的头开始 */
47 while(p != NULL){ /* 当链表没有结束时 */
48 Node q;
49 q = p;
50 p = p->next; /* 释放链表的每一个结点 */
51 free(q);
52 }
53 head = NULL; /* 将头结点置空 */
54 }
55 int main(void)
56 {
57 Node p;
58 int i;
59 int res = -1;
60 printf("insert\n");
61 for(i = 1; i< 8; i++) /* 插入链表结点 */
62 if(insert(i) == -1)
63 goto err; /* 出错则跳到err处进行资源释放 */
64 print(); /* 遍历链表,打印链表结点 */
65 res = 0;
66 err:
67 destroy(); /* 销毁链表 */
68 return res; /* 程序结束状态 */
69 }