1 /*本程序是单链表的创建,其中包括:单链表初始化,链表长度的判断,链表的插入、链表删除、链表取出、链表销毁等*/
2 #include <stdio.h>
3 #include <malloc.h>//涉及到动态分配内存,所以要定义头文件
4 #include <stdlib.h>
5
6 //定义抽象类型
7 typedef int DataType;
8 //定义节点
9 typedef struct node{
10
11 DataType data;
12 struct node *next;
13 }SLNode;
14
15 //初始化链表
16 void LinkInit(SLNode **head)
17 {
18 if ((*head = (SLNode *)malloc(sizeof(SLNode))) == NULL)//特别容易犯错误的地方,应该将(*head = (SLNode *)malloc(sizeof(SLNode)))加外括号
19 {
20 exit(1);
21 }
22 (*head)->next = head;
23 }
24
25 //判断链表的长度
26 int LinkLength(SLNode *head)
27 {
28 SLNode *p=head;
29 int num=0;
30
31 while (p->next!=head)
32 {
33
34 p = p->next;
35 num++;
36
37 }
38 return num;
39 }
40
41 //插入链表
42 int LinkInsert(SLNode *head, int i, DataType x)
43 {
44 SLNode *p, *q;
45 int j = -1;
46
47 if((q = (SLNode*)malloc(sizeof(SLNode)))==NULL) exit(1);
48
49 p = head;
50 while (p->next!=head&&j<i-1)//i-1
51 {
52 p = p->next;
53 j++;
54 }
55 if (j!=i-1)
56 {
57 printf("error!");
58 return 0;
59 }
60
61 q->data = x;
62
63 q->next = p->next;
64 p->next = q;
65 return 1;
66
67 }
68
69 //删除链表
70 int LinkDelete(SLNode *head, int i, DataType *x)
71 {
72 SLNode *p,*q;
73 int j = -1;
74
75 p = head;
76 while (p->next!=head&&p->next->next!=NULL&&j<i-1)
77 {
78 p = p->next;
79 j++;
80 }
81 if (j != i-1)
82 {
83 printf("error!");
84 return 0;
85 }
86 q = p->next;
87 *x = q->data;
88
89 p->next = p->next->next;
90 free(q);
91 return 1;
92 }
93
94 //取出链表
95 int LinkGet(SLNode *head, int i,DataType *x)
96 {
97 SLNode *p;
98 int j = -1;
99
100 p = head;
101 while (p->next!=head&&j<i)
102 {
103 j++;
104 p = p->next;
105 }
106 if (j != i)
107 {
108 printf("error!");
109 return 0;
110 }
111 else
112 {
113 *x = p->data;
114 return 1;
115 }
116 }
117
118 //清空链表
119 void LinkDestroy(SLNode **head)
120 {
121 SLNode *p, *newp;
122
123 p = *head;
124 while (p!=head)
125 {
126 newp = p;
127 p = p->next;
128 free(newp);
129 }
130 *head = NULL;
131 }
132
133
134 //主函数 应用
135
136 int main()
137 {
138 SLNode *mylist;
139 int i,x;
140
141 LinkInit(&mylist);
142 for ( i = 0; i < 10; i++)
143 {
144 if (LinkInsert(mylist,i,i+1)==0)
145 {
146 printf("插入error!\n");
147 getchar();
148 return;
149 }
150 }
151 if (LinkDelete(mylist, 4, &x) == 0)
152 {
153 printf("error!\n");
154 return;
155 }
156 else
157 {
158 printf("删除数字:%d\n", x);
159 }
160 for ( i = 0; i < 9; i++)
161 {
162 if (LinkGet(mylist, i, &x) == 0)
163 {
164 printf("error!\n");
165 return;
166 }
167 else
168 {
169 printf("%d ", x);
170 }
171 }
172 LinkDestroy(&mylist);
173 getchar();
174 getchar();
175 return 0;
176 }