Skip to main content

Insert node at first position in doubly link list

Now we will see how to insert a new node at first position in doubly link list.

Algorithm for insertion at first position in doubly link list:

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

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


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

 

Program to insert at first position in the doubly link list:


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

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

void insertAtFirst(NODE **, int);
void traverse(NODE **);

int main(){
 NODE *start = NULL;
 
 insertAtFirst(&start, 5);
 insertAtFirst(&start, 3);
 traverse(&start);
 return 0;
}

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

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

 
2  1
 

Comments