Delete Last 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 node and then linked list becomes empty (FIRST=NULL).
(3) There are more then one nodes in the linked list. In this case we have to traverse from first node to last node and then delete the last node. After deleting the last node we have to set NULL value in the LINK part of the previous node.

Algorithm to Delete Last 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
           SAVE=FIRST
           Repeat while SAVE->LINK ≠ NULL
           PRED=SAVE
           SAVE=SAVE->LINK
           Return SAVE->INFO
           PRED->LINK=NULL
Step 3: Exit


     

Program to Delete Last 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 dellast()
{
     struct node *SAVE,*PRED;
     if (FIRST==NULL)
     printf("Linked List is Empty");
     else if(FIRST->link==NULL)
     {
          printf("Deleted element is %d",FIRST->info);
          FIRST=NULL;
     }
     else
     {   SAVE=FIRST;
          while(SAVE->link!=NULL)
          {
          PRED=SAVE;
          SAVE=SAVE->link;
          }
          printf("Deleted element is %d\n",SAVE->info);
          PRED->link=NULL;
     }

}
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();
dellast();
display();
getch();
}

Download Projects


Download Programs