1 #include <stdio.h>
2 #include <stdlib.h>
3
4 struct Node
5 {
6 struct Node *next;
7 int num;
8 };
9
10 struct Node *list = NULL;
11
12 /**
13 * 初始化链表
14 */
15 void initList()
16 {
17 list = (struct Node *)malloc(sizeof(struct Node));
18 list->next = NULL;
19 }
20
21 /**
22 *添加链表元素
23 */
24 void addList(int i)
25 {
26 struct Node *p = (struct Node*)malloc(sizeof(struct Node));
27 p->num = i;
28 p->next = list;
29 list = p;
30 }
31
32 /**
33 *打印链表内容
34 */
35 void printfList()
36 {
37 int i =0;
38 struct Node *p = list;
39 while(p->next !=NULL)
40 {
41 i++;
42 printf("num = %d\n",p->num);
43 p = p->next;
44 }
45 }
46
47 /**
48 * 获得链表长度
49 */
50 int getListLength()
51 {
52 int length = 0;
53 struct Node *node = list;
54 while(node->next != NULL)
55 {
56 length++;
57 node = node->next;
58 }
59
60 return length;
61 }
62
63 /**
64 *插入数据到链表
65 */
66 int insertToList(int position ,int num)
67 {
68 int length = getListLength();
69
70 if(position >length-1)
71 {
72 return -1;
73 }
74
75 if(position == length-1)
76 {
77 struct Node *node = (struct Node *)malloc(sizeof(struct Node));
78 node->num = num;
79 node->next = list;
80 list = node;
81 return 0;
82 }
83 else
84 {
85 /* int i=0;
86
87 struct Node *node = list;
88 while(i<position)
89 {
90 node = node->next;
91 }
92
93 struct Node *p = (struct Node *)malloc(sizeof(struct Node));
94 p->num = num;
95 p->next = node->next;
96 node->next = p;
97 */
98 return 0;
99 }
100
101 }
102
103 /**
104 *逆序链表
105 */
106 void inversionToList()
107 {
108 struct Node *p,*q,*front;
109 p = list;
110
111 while(p!=NULL)
112 {
113 q = p->next;
114 p->next = front;
115 front = p;
116 p =q;
117 }
118
119 list = p;
120 }
121
122
123 /**
124 *查找给定的元素
125 */
126 int findListData(int key)
127 {
128 struct Node *node = list;
129 int i = 0;
130 while(node->next !=NULL)
131 {
132
133 if(node->num == key)
134 {
135 goto find;
136 }
137 node = node->next;
138 i++;
139 }
140 find:
141 return i;
142 }
143
144 int main()
145 {
146 initList();
147
148 int i = 0;
149 for(i = 0;i<6;i++)
150 {
151 addList(i);
152 }
153
154 printf("list length = %d\n",getListLength());
155
156 printf("find position = %d\n",findListData(2));
157
158 if(-1 == insertToList(2,19))
159 {
160 printf("error\n");
161 }
162
163 printfList();
164 inversionToList();
165
166 }
以上主要完成了链表的基本操作,还需要将链表的插入稍作修改