Here we are going to write a c program to delete a node after a given node from a singly linked list. But before deletion we must have a proper linked list so we can either create a linked list or insert elements in our linked. Insertion can be various kinds like insert at head, insert at end, insert before or after given node etc. You can follow anything, in this program we will insert at end after that we will delete. Again deletion can be from the beginning, from the end or after a given node but in this post we are concerned about deleting node after a given node.
Before we proceed, if you don't have basic knowledge of linked list or want to learn everything about singly linked list at one go then you must visit singly linked list post which is a part of our dsa series and also types of linked list series.
Ok Now How will we do this means deletion of node after a given node from a singly linked list.
First we will take a pointer variable temp and initialize it with HEAD i.e., now temp points to the first node of the linked list. In while loop we will traverse through the linked list till we reach the value of node after which we want to delete node. Once reached we will store it in a pointer variable del and change the next pointer in such a way that the node is deleted after desired node. Then finally we will free the memory occupied by the node and return to the free pool.
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node* next;
};
void insertatend(struct node** head)
{
int n;
printf("Enter value to insert at end: ");
scanf("%d",&n);
struct node* val=(struct node*)malloc(sizeof(struct node));
val->data=n;
val->next=NULL;
if(*head==NULL)
{
*head=val;
return;
}
struct node* t=*head;
while(t->next!=NULL)
{
t=t->next;
}
t->next=val;
}
void deleteathead(struct node** head)
{
if(*head==NULL)
{
return;
}
struct node* del=*head;
*head=(*head)->next;
free(del);
}
void deletenode(struct node** head)
{
int n;
printf("Enter the value of node whose next you want to delete: ");
scanf("%d",&n);
if(*head==NULL)
{
return;
}
if((*head)->next==NULL)
{
deleteathead(head);
return;
}
struct node* temp=*head;
while(temp->data!=n)
{
temp=temp->next;
}
struct node* del=temp->next;
temp->next=temp->next->next;
free(del);
}
void display(struct node* head)
{
struct node* t=head;
while(t!=NULL)
{
printf("%d => ",t->data);
t=t->next;
}
printf("NULL \n");
}
int main()
{
struct node* head=NULL;
insertatend(&head);
insertatend(&head);
insertatend(&head);
display(head);
deletenode(&head);
display(head);
return 0;
}Enter value to insert at end: 4
Enter value to insert at end: 5
Enter value to insert at end: 6
4 => 5 => 6 => NULL
Enter the value of node whose next you want to delete: 5
4 => 5 => NULL
Post a Comment
If you have any doubts, please let me know