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

  
Algorithm to delete last node in singly link list:
- Set TEMP = START
- If START != NULL - If list has only one node i.e. [START->NEXT == NULL ] - Set START = NULL
 
- Else - Traverse the list so that TEMP points to second last node
- Make second last node point to nothing i.e. [TEMP->NEXT = NULL]
 
- End If
 
- If list has only one node i.e. [START->NEXT == NULL ] 
- End If

Function to delete last node in singly link list:
int deleteLast(NODE **start){
 NODE *temp = *start;
 int info = -1;
 if(*start == NULL){
  printf("\nNo nodes exists in the list");
 }
 else if((*start)->next == NULL){
  info = (*start)->info;
  free(*start);
  *start = NULL;
 }
 else{
  while(temp->next->next != NULL){
   temp = temp->next;
  }
  info = temp->next->info;
  free(temp->next);
  temp->next = NULL;
 }
 return info;
}
Program to delete last node in the singly link list:
#include <stdio.h>
#include <malloc.h>
struct node{
 int info;
 struct node *next;
};
typedef struct node NODE;
void insertAtFirst(NODE **, int);
int deleteLast(NODE **);
void traverse(NODE **);
int main(){
 
 NODE *start = NULL;
 
 insertAtFirst(&start, 4);
 insertAtFirst(&start, 5); 
 traverse(&start);
 deleteLast(&start);
 printf("\n");
 traverse(&start);
 return 0;
}
int deleteLast(NODE **start){
 NODE *temp = *start;
 int info = -1;
 if(*start == NULL){
  printf("\nNo nodes exists in the list");
 }
 else if((*start)->next == NULL){
  info = (*start)->info;
  free(*start);
  *start = NULL;
 }
 else{
  while(temp->next->next != NULL){
   temp = temp->next;
  }
  info = temp->next->info;
  free(temp->next);
  temp->next = NULL;
 }
 return info;
}
void insertAtFirst(NODE **start, int info){
 NODE *ptr = (NODE*) malloc(sizeof(NODE));
 ptr->info = info;
 ptr->next = *start;
 *start = ptr; 
}
void traverse(NODE **start){
 NODE *temp;
 temp = *start;
 while(temp != NULL){
  printf("%d  ", temp->info);
  temp = temp->next;
 }
}
5 4 5
Comments
Post a Comment