Skip to main content

Insert node at last position in doubly link list

Now we will see how to insert a new node at the last position of doubly link list.

Algorithm for insertion at last position in doubly link list:

In this algorithm, START is pointer to first node of list and PTR is the node to be inserted at last. The steps are as follows:
  • Create new node PTR
  • Set the info field of PTR
  • Set PTR->NEXT = NULL
  • If list is empty i.e. START == NULL
    • Set START = PTR
    • Set PTR->PREV = NULL
  • Else
    • Traverse the list for last node into TEMP pointer
    • Set PTR->PREV = TEMP
    • Set TEMP->NEXT = PTR
  • End If;
 



 

Function to insert node at last position in doubly link list:


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;
 }
}

 

Program to insert at last position 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);
void traverse(NODE **);

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

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;
 }
}

 
1  2  3
 

Comments