Delete First Node From Linked List


In order to delete first node from linked list we have to consider three possibilities:
(1) List is Empty (FIRST = NULL). In this case we can not delete node from linked list.
(2) There is only one node in the linked list (FIRST->LINK=NULL). In this case we can delete the first node and then linked list becomes empty (FIRST=NULL).
(3) There are more then one nodes in the linked list. In this case we can delete the first node. After deleting the first node we have to move FIRST pointer to next node so that it can points to the newly first node in the linked list.

     

Algorithm to Delete First Node From Linked List


Step 1: If FIRST = NULL then
           Write “Linked List is Empty”
Step 2: If FIRST->LINK = NULL then
           Return FIRST->INFO
           FIRST=NULL
           Else
           Return FIRST->INFO
           FIRST=FIRST->LINK
Step 3: Exit


Program to Delete First Node From Linked List


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
      int info;
      struct node *link;
};
struct node *FIRST;
void createlist()
{
      char ch;
      printf("Enter n for break:\n");
      scanf("%c",&ch);
      while(ch!='n')
      {
      struct node *NEW_NODE,*SAVE;int x;
      NEW_NODE=(struct node *)malloc(sizeof(struct node));
      printf("Enter Data:");
      scanf("%d",&x);
      NEW_NODE->info=x;
      if(FIRST==NULL)
      {
         NEW_NODE->link=NULL;
         FIRST=NEW_NODE;
      }
      else
      {
         SAVE=FIRST;
         while(SAVE->link!=NULL)
         {
            SAVE=SAVE->link;
         }
         SAVE->link=NEW_NODE;
         NEW_NODE->link=NULL;
      }
      fflush(stdin);
      printf("Enter n for break:\n");
      scanf("%c",&ch);
   }
}
void delfirst()
{
     struct node *SAVE;
     if (FIRST==NULL)
          printf("Linked List is Empty");
     else if(FIRST->link==NULL)
     {
          printf("Deleted element is %d",FIRST->info);
          FIRST=NULL;
     }
     else
     {
          printf("Deleted element is %d",FIRST->info);
          FIRST=FIRST->link;
     }

}
void display()
{
struct node *SAVE;
if(FIRST==NULL)
{
printf("sll is empty\n");
return;
}
printf("elements are:\n");
SAVE=FIRST;
while(SAVE!=NULL)
{
if(SAVE->link==NULL)
printf("|%d|",SAVE->info);
else
printf("|%d|->",SAVE->info);
SAVE=SAVE->link;
}
printf("\n");
return;
}
void main()
{
clrscr();
FIRST=NULL;
createlist();
display();
delfirst();
display();
getch();
}

Download Projects


Download Programs