Deleting A Node In Linked List
In this post, you will learn how to delete a node in the Linked List, Code for the above task given below:
void delete(struct node **head, int b){
struct node *del;
if ((*head)->data==b)
{
del = *head;
*head = (*head)->next;
free(del);
}
else{
struct node *p = *head;
while (p->next!=NULL)
{
if(p->next->data==b){
del = p->next;
p->next = p->next->next;
free(del);
}
else{
p = p->next;
}
}
}
}
In this program, we are doing following things:
- In deletion we are finding the data as key, if key is in head then we have to make the head as another node called del.
- We need to make the second node as head, and delete the del node.
- If the key is not in the head, then we have to traverse and find if the next pointer which points to another node has data equal to key.
- If yes then make the next node as temp and and update the address of next in the previous node.
- Delete del node by free method.
- The traversing will be from head to second last node.
- Suppose if we need to delete the last node, then we can use second last node to delete it.
So this is how the function is working.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
void add(struct node **head, int a){
struct node *new = malloc(sizeof(struct node));
new->data = a;
new->next = NULL;
if(*head==NULL){
*head = new;
}
else{
struct node *temp = *head;
while (temp->next!=NULL)
{
temp = temp -> next;
}
temp->next = new;
}
}
void delete(struct node **head, int b){
struct node *del;
if ((*head)->data==b)
{
del = *head;
*head = (*head)->next;
free(del);
}
else{
struct node *p = *head;
while (p->next!=NULL)
{
if(p->next->data==b){
del = p->next;
p->next = p->next->next;
free(del);
}
else{
p = p->next;
}
}
}
}
void print(struct node **head){
struct node *pri = *head;
while (pri!=NULL)
{
printf("%d ",pri->data);
pri = pri->next;
}
}
int main(){
struct node *head = NULL;
add(&head, 1);
add(&head, 2);
add(&head, 3);
int b;
scanf("%d",&b);
delete(&head, b);
print(&head);
return 0;
}