上一篇已经讲过链表的初始化、头插头删、尾插尾删等工作。
这一篇主要讲链表的任意位置的增删查改。
一:给定一个值,在链表中找到它的位置
113 LinkNode* LinkListFind(LinkNode* head, LinkNodeType to_find)
114 {
115 //find a value
116 if(head == NULL)
117 return NULL;
118 LinkNode* cur = head;
119 for(;cur != NULL;cur = cur->next)
120 {
121 if(cur->data == to_find)
122 return cur;
123 }
124 return NULL;
125 }
思路如下:遍历链表
(指针的传入,都需要判断其合法性,之后不再赘述)
1.这个值在链表中存在:找到其值,返回地址。
2.这个值在链表中不存在:直接返回NULL。
二:在给定位置之后插入一个给定值。
128 void LinklistInsertAfter(LinkNode** head, LinkNode* pos, LinkNodeType value)
129 {
130 // insert value after pos
131 if (head == NULL)
132 return ;
133 if (*head == NULL)
134 return ;
135 if (pos == NULL)
136 return ;
137 LinkNode* cur = *head;
138 while(cur != pos && cur != NULL)
139 {
140 cur = cur->next;
141 }
142 if (cur == NULL)
143 return;
144 else
145 {
146 LinkNode* new_node = CreatNode(value);
147 new_node->next = cur->next;
148 cur->next = new_node;
149 }
150
151 }
思路如下:遍历链表
1. pos值存在:创建以给定值的新节点,插入pos后
2.pos值不存在:直接return;
三:在给定位置之前插入一个给定值。
153 void LinklistInsertBefore(LinkNode** head, LinkNode* pos, LinkNodeType value)
154 {
155 // insert value before pos
156 if (head == NULL)
157 return ;
158 if (*head == NULL)
159 return ;
160 if (pos == NULL)
161 return ;
162 if (pos == *head)
163 {
164 LinkNode* new_node = CreatNode(value);
165 new_node->next = *head;
166 *head = new_node;
return;
167 }
168 LinkNode* cur = *head;
169