@@ -113,7 +113,7 @@ void insert_middle(int value,int position)
113
113
* DELETION
114
114
* 1. FROM HEAD
115
115
* 2. FROM TAIL
116
- * 3A. FROM MIDDLE USING VALUE
116
+ * 3A. FROM MIDDLE USING VALUE FROM LEFT
117
117
* 3B. FROM MIDDLE USING INDEX
118
118
*=======================================/
119
119
@@ -165,8 +165,83 @@ void delete_tail()
165
165
}
166
166
167
167
/*===> DELETE FROM MIDDLE USING VALUE <===*/
168
+ void delete_using_value (int value )
169
+ {
170
+ if (head == NULL )
171
+ {
172
+ return ;
173
+ }
174
+ else if (head -> next == NULL && head -> value == value ) //one node
175
+ {
176
+ head = NULL ;
177
+ }
178
+ else if (head -> value == value ) //value present at head
179
+ {
180
+ struct node * temp = head ;
181
+ head = head -> next ;
182
+ temp -> next = NULL ;
183
+ free (temp );
184
+ }
185
+ else
186
+ {
187
+ struct node * current = head ;
188
+ struct node * prev = head ;
189
+ while (current -> next != NULL )
190
+ {
191
+ if (current -> value == value )
192
+ {
193
+ break ;
194
+ }
195
+ prev = current ;
196
+ current = current -> next ;
197
+ }
198
+ prev -> next = current -> next ;
199
+ current -> next = NULL ;
200
+ free (current );
201
+ }
202
+ length -- ;
203
+ }
168
204
169
205
/*===> DELETE FROM MIDDLE USING INDEX <===*/
206
+ void delete_using_index (int position )
207
+ {
208
+ if (head == NULL )
209
+ {
210
+ return ;
211
+ }
212
+ else if (position < 0 || position > length - 1 )
213
+ {
214
+ printf ("INVALID POSITION\n" );
215
+ return ;
216
+ }
217
+ else if (position == 0 ) //deletion at head
218
+ {
219
+ struct node * temp = head ;
220
+ head = head -> next ;
221
+ temp -> next = NULL ;
222
+ free (temp );
223
+ }
224
+ else
225
+ {
226
+ int i = 0 ;
227
+ struct node * current = head ;
228
+ struct node * prev = head ;
229
+ while (current -> next != NULL )
230
+ {
231
+ if (i == position )
232
+ {
233
+ break ;
234
+ }
235
+ i ++ ;
236
+ prev = current ;
237
+ current = current -> next ;
238
+ }
239
+ //deletion
240
+ prev -> next = current -> next ;
241
+ current -> next = NULL ;
242
+ free (current );
243
+ }
244
+ }
170
245
171
246
/***********************************/
172
247
/*=========> PRINT LIST <=========*/
@@ -206,4 +281,11 @@ int main()
206
281
print_single_linked_list ();
207
282
208
283
printf ("%d %d\n" ,length ,size ());
284
+
285
+ delete_using_value (1 );
286
+ delete_using_value (3 );
287
+ print_single_linked_list ();
288
+
289
+ delete_using_index (-1 );
290
+ print_single_linked_list ();
209
291
}
0 commit comments