Deletion in A Linked List
Deletion in A Linked List
free(ptr);
The above syntax will free this node, that is, remove its reserved
location in the heap.
Now, let's begin with each of these cases of deletion.
Similar to the other cases, ptr can be deleted for a given value
as well by following few steps:
1. p->next = givenVal-> next;
2. free(givenVal);
Since, the value 8 comes twice in the list, this function will be
made to delete only the first occurrence.
And the same goes with case 3 and case 4. We have to traverse
through the list to reach that desired position.
free(ptr);
return head;
// Case 2: Deleting the element at a given index from the linked list
p = p->next;
q = q->next;
p->next = q->next;
free(q);
return head;
while(q->next !=NULL)
p = p->next;
q = q->next;
p->next = NULL;
free(q);
return head;
}
Deleting the element with a given value from the linked list :
// Case 4: Deleting the element with a given value from the linked list
p = p->next;
q = q->next;
if(q->data == value){
p->next = q->next;
free(q);
return head;
So, this was all about deletion in the linked list data structure.Here
is the whole source code:
#include <stdio.h>
#include <stdlib.h>
struct Node
int data;
};
ptr = ptr->next;
}
// Case 1: Deleting the first element from the linked list
head = head->next;
free(ptr);
return head;
// Case 2: Deleting the element at a given index from the linked list
p = p->next;
q = q->next;
p->next = q->next;
free(q);
return head;
while(q->next !=NULL)
p = p->next;
q = q->next;
p->next = NULL;
free(q);
return head;
// Case 4: Deleting the element with a given value from the linked list
p = p->next;
q = q->next;
if(q->data == value){
p->next = q->next;
free(q);
return head;
int main()
head->data = 4;
head->next = second;
second->data = 3;
second->next = third;
third->data = 8;
third->next = fourth;
fourth->data = 1;
fourth->next = NULL;
linkedListTraversal(head);
linkedListTraversal(head);
return 0;