单链表的实现:增删改查

  1 /*
2 *@author ?
3 *@since 2011/07/29
4 *@function 实现链表的常用操作,比较粗糙。
5 * 功能大概是:显示链表结构;查询链表;删除节点;插入结点;修改结点
6 */
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 struct node
11 {
12 int value;
13 struct node *next;
14 };
15 /*
16 *插入结点(单个)
17 */
18 struct node *add_to_list(struct node *list,int n)
19 {
20 struct node *new_node;
21
22 new_node=malloc(sizeof(struct node));
23 if(new_node==NULL)
24 {
25 printf("Error:malloc failed in add_to_list\n");
26 exit(EXIT_FAILURE);
27 }
28 new_node->value=n;
29 new_node->next=list;
30
31 return new_node;
32 }
33 /*
34 *添加结点(多个)
35 */
36 struct node *read_numbers(void)
37 {
38 struct node *first=NULL;
39 int n;
40
41 printf("Enter a series of integers (0 to terminate): ");
42 for(;;)
43 {
44 scanf("%d",&n);
45 if(n==0)
46 {
47 return first;
48 }
49 first=add_to_list(first,n);
50 }
51 }
52 /*
53 *搜索结点
54 */
55 struct node *search_list(struct node *list,int n)
56 {
57 struct node *p;
58
59 for(p=list;p!=NULL;p=p->next)
60 if(p->value==n)
61 return p;
62
63 return NULL;
64 }
65 /*
66 *删除结点
67 */
68 struct node *delete_node(struct node *list,int n)
69 {
70 struct node *cur,*prev;
71
72 for(cur=list,prev=NULL;
73 cur!=NULL&&cur->value!=n;
74 prev=cur,cur=cur->next)
75 ;
76 if(cur==NULL)
77 {
78 return list;
79 }
80 if(prev==NULL)
81 {
82 list=list->next;
83 }else
84 {
85 prev->next=cur->next;
86 }
87 free(cur);
88
89 return list;
90 }
91 /*
92 *修改结点
93 */
94 struct node *update_node(struct node *list,int n)
95 {
96 struct node *cur;
97 int new_value;
98
99 for(cur=list;cur!=NULL&&cur->value!=n;cur=cur->next)
100 ;
101 if(cur==NULL)
102 {
103 printf("NO NODE!!!");
104 }
105 printf("please enter the new value: ");
106 scanf("%d",&new_value);
107 cur->value=new_value;
108
109 return list;
110 }
111 /*
112 *打印链表结点结构
113 */
114 void print(struct node *list)
115 {
116 struct node *p;
117
118 printf("The current relation of the list is ");
119
120 for(p=list;p!=NULL;p=p->next)
121 {
122 if(p->next!=NULL)
123 {
124 printf("%d->",p->value);
125 }else
126 {
127 printf("%d\n",p->value);
128 }
129 }
130 }
131
132 int main()
133 {
134 struct node *test,*p;
135 int n;
136
137 test=read_numbers();
138
139 /*
140 *输出当前链表
141 */
142 print(test);
143
144 /*
145 *查找链表中结点,并输出结点的值
146 */
147 printf("Please enter the value to look for: ");
148 scanf("%d",&n);
149 p=search_list(test,n);
150 printf("The value of the node is %d\n",p->value);
151
152 /*
153 *删除结点并显示更新后链表的结构
154 */
155 printf("Please choose the value of the node you would like to delete: ");
156 scanf("%d",&n);
157 p=delete_node(test,n);
158 print(p);
159
160 /*
161 *修改结点并显示更新后链表的结构
162 */
163 printf("Please choose the value of the node you would like to update: ");
164 scanf("%d",&n);
165 p=update_node(test,n);
166 print(p);
167
168 return 0;
169 }


结果如下:

posted @ 2011-07-29 18:08  KISS's blog  阅读(2449)  评论(1编辑  收藏  举报