Skip to main content

Deletion of last node in doubly link list

Now we will see how to delete node at last position in doubly link list.

Algorithm to delete node at last position in doubly link list:

  • Declare TEMP = START
  • If list have only one node i.e. START->NEXT = NULL
    • Set START = NULL
  • Else
    • Traverse the list for last node in the list into TEMP pointer
    • Set TEMP->PREV->NEXT = NULL
  • Free (TEMP)
  • End If;

Function to delete last node in doubly link list:

 

int deleteAtLast(NODE **start){
 NODE *temp = *start;
 int info = -1;
 if(*start == NULL){
  printf("\nError: No nodes");
 }
 else if((*start)->next == NULL){
  info = (*start)->info;
  free(*start);
  *start = NULL;
 }
 else{
  while(temp->next != NULL){
   temp = temp->next;
  }
  temp->prev->next = NULL;
  info = temp->info;
  free(temp);
 }
 return info;
}

 

Program to delete last node in the doubly link list:

 

#include <stdio.h>
#include <malloc.h>

typedef struct node{
 int info;
 struct node *next, *prev;
} NODE;

void insertAtLast(NODE **, int);
int deleteAtLast(NODE **);
void traverse(NODE **);

int main(){
 
 NODE *start = NULL;
 
 insertAtLast(&start, 1);
 insertAtLast(&start, 2);
 traverse(&start);
 
 deleteAtLast(&start);
 traverse(&start);
 
 deleteAtLast(&start);
 traverse(&start);
 
 deleteAtLast(&start);
 traverse(&start);
  
 return 0;
}

int deleteAtLast(NODE **start){
 NODE *temp = *start;
 int info = -1;
 if(*start == NULL){
  printf("\nError: No nodes");
 }
 else if((*start)->next == NULL){
  info = (*start)->info;
  free(*start);
  *start = NULL;
 }
 else{
  while(temp->next != NULL){
   temp = temp->next;
  }
  temp->prev->next = NULL;
  info = temp->info;
  free(temp);
 }
 return info;
}

void insertAtLast(NODE **start, int info){
 NODE *ptr = (NODE*) malloc(sizeof(NODE));
 NODE *temp = *start;
 ptr->info = info;
 ptr->next = NULL;
 if(*start == NULL){
  *start = ptr;
  ptr->prev = NULL;
 }
 else{
  while(temp->next != NULL){
   temp = temp->next;
  }
  ptr->prev = temp;
  temp->next = ptr;
 }
}

void traverse(NODE **start){
 NODE *temp = *start;
 while(temp != NULL){
  printf("%d  ", temp->info);
  temp = temp->next;
 }
 printf("\n");
}

 
1  2
1
Error: No nodes
 

Comments