Delete A Node In Linked List In C

Hello Coders! Welcome to nkcoderz blog. 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:

  1. 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.
  2. We need to make the second node as head, and delete the del node.
  3. 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.
  4. If yes then make the next node as temp and and update the address of next in the previous node.
  5. Delete del node by free method.
  6. The traversing will be from head to second last node.
  7. 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;
}

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment