1 #include <stdio.h>
2 #include <malloc.h>
3 typedef struct lianbiao *ptr;
4 struct lianbiao
5 {
6 int data;
7 ptr next;
8 };
9
10 int main(void)
11 {
12 ptr create();
13 void out(ptr p);
14 ptr search(ptr p, int x);
15 ptr del(ptr h, int x);
16 ptr add(ptr head, int x);
17 int delEl, searchEl, addEl, delResult, searchResult;
18
19 ptr l = create(); //构建初始链表
20
21 printf("初始链表为:"); //输出初始链表
22 out(l);
23 printf("\n");
24
25 //查找元素
26 printf("输入待查找元素:");
27 scanf("%d", &searchEl);
28
29 searchResult = search(l, searchEl);
30 if (searchResult)
31 {
32 searchResult = search(l, searchEl)->data;
33 printf("元素%d查找成功\n", searchResult);
34 }
35
36 else
37 printf("待查找元素不存在!\n");
38 printf("\n");
39
40 //删除元素
41 printf("输入待删除元素:");
42 scanf("%d", &delEl);
43 delResult = del(l, delEl);
44 if (delResult)
45 printf("删除成功!\n");
46 else
47 printf("待删除元素不存在!\n");
48 printf("\n");
49
50 //插入元素
51 printf("输入待插入元素:");
52 scanf("%d", &addEl);
53 add(l, addEl);
54 }
55
56 ptr create() // 构建链表
57 {
58 ptr p, head, last;
59 int x;
60 //创建头结点
61 head = (ptr)malloc(sizeof(ptr));
62 head->data = 0;
63 last = head;
64 last->next = NULL;
65
66 //添加链表元素
67 printf("构建初始链表(输入0以结束):");
68 scanf("%d", &x);
69 while (x != 0)
70 {
71 p = (ptr)malloc(sizeof(ptr));
72 p->data = x;
73
74 //把新元素插入链表
75 if (x > last->data) //待插入元素大于所有节点
76 {
77 last->next = p;
78 p->next = NULL;
79 last = p;
80 }
81 else if (x < head->next->data) //待插入元素小于所有节点
82 {
83 p->next = head->next;
84 head->next = p;
85 }
86 else //一般情况
87 {
88 ptr f = head, s = f->next;
89 while (x > s->data)
90 {
91 f = s;
92 s = s->next;
93 }
94 p->next = s;
95 f->next = p;
96 }
97
98 scanf("%d", &x);
99 }
100 return head;
101 }
102
103 void out(ptr p) //输出链表
104 {
105 p = p->next;
106 while (p != NULL)
107 {
108 printf("%5d", p->data);
109 p = p->next;
110 }
111 printf("\n");
112 };
113
114 ptr search(ptr p, int x) //搜索元素
115 {
116 while (p != NULL)
117 {
118 if (p->data == x)
119 return p;
120 p = p->next;
121 }
122 return 0;
123 }
124
125 ptr del(ptr h, int x) //删除元素
126 {
127 ptr f, s;
128 f = h;
129 s = h->next;
130 while (s->data != x)
131 {
132 f = s;
133 s = s->next;
134 if (s->next == NULL)
135 break;
136 }
137
138 if (s->data == x)
139 {
140 f->next = s->next;
141 free(s);
142 return 1;
143 }
144 else
145 return 0;
146 }
147
148 ptr add(ptr head, int x)
149 {
150 ptr p, last, yyy;
151 yyy = head;
152 while (yyy->next != NULL)
153 yyy = yyy->next;
154 last = yyy;
155 last->next = NULL;
156
157 p = (ptr)malloc(sizeof(ptr));
158 p->data = x;
159
160 //把新元素插入链表
161 if (x > last->data) //待插入元素大于所有节点
162 {
163 last->next = p;
164 p->next = NULL;
165 last = p;
166 }
167 else if (x < head->next->data) //待插入元素小于所有节点
168 {
169 p->next = head->next;
170 head->next = p;
171 }
172 else //一般情况
173 {
174 ptr f = head, s = f->next;
175 while (x > s->data)
176 {
177 f = s;
178 s = s->next;
179 }
180 p->next = s;
181 f->next = p;
182 }
183
184 printf("添加完成!\n现在的链表为:");
185 out(head);
186 printf("\n");
187 }