Deletion in singly linked list at the beginning

With a few adjustments in the node pointers, we can delete a node from the beginning of the list. It is thus the most simplistic operation of all. Here, we need to delete the first node of the list. For which, we will use the below statements to make the head point to the next of the head.

ptr = head;  
head = ptr->next;

Now, by using the below statement, we can free the pointer ptr which was pointing to the head node of the list.

free(ptr)

Algorithm:

  • Step 1:
    IF HEAD = NULL
    Write UNDERFLOW
    Go to Step 5
  • Step 2: SET PTR = HEAD
  • Step 3: SET HEAD = HEAD -> NEXT
  • Step 4: FREE PTR
  • Step 5: EXIT

Example in C:

#include<stdio.h>  
#include<stdlib.h>  
 
void create(int);  
void deleteNode();  
struct node  
{  
    int data;  
    struct node *next;  
};  
struct node *head;  
void main ()  
{  
    int choice,item;  
    do   
    {  
        printf("\n1.Insert Node\n2.Delete Node\n3.Exit\n4.Enter your choice:\n");  
        scanf("%d",&choice);  
        switch(choice)  
        {  
            case 1:  
            printf("\nEnter the element:\n");  
            scanf("%d",&item);  
            create(item);  
            break;   
            case 2:  
            deleteNode();  
            break;   
            case 3:  
            exit(0);  
            break;    
            default:  
            printf("\nPlease enter a valid choice:\n");  
        }  
 
    }while(choice != 3);  
}  
void create(int item)  
    {  
        struct node *ptr = (struct node *)malloc(sizeof(struct node *));  
        if(ptr == NULL)  
        {  
            printf("\nOVERFLOW\n");  
        }  
        else  
        {  
            ptr->data = item;  
            ptr->next = head;  
            head = ptr;  
            printf("\nNode inserted successfully!!\n");  
        }  
 
    }  
void deleteNode()  
    {  
        struct node *ptr;  
        if(head == NULL)  
        {  
            printf("\nKindly Check. The list is empty.");  
        }  
        else   
        {  
            ptr = head;  
            head = ptr->next;  
            free(ptr);  
            printf("\nNode successfully deleted from the beginning of the list!!");  
        }  
    }

Output:

1.Insert Node
2.Delete Node
3.Exit
4.Enter your choice:
1
 
Enter the element:
2
 
Node inserted successfully!!
 
1.Insert Node
2.Delete Node
3.Exit
4.Enter your choice:
1
 
Enter the element:
3
 
Node inserted successfully!!
 
1.Insert Node
2.Delete Node
3.Exit
4.Enter your choice:
2
 
Node successfully deleted from the beginning of the list!!
1.Insert Node
2.Delete Node
3.Exit
4.Enter your choice:
3