Insert New node at the beginning of the Doubly Linked List

Insert New node at the beginning of the Doubly Linked List

In this post, you will learn how to insert new node at the beginning of the Doubly Linked List, Code for the above task given below:


Insert New node at the beginning of the Doubly Linked List

struct node{
    struct node *prev;
    int data;
    struct node *next;
};

struct node *head = NULL; void insertElementAtBeginning(int val){ struct node *new = malloc(sizeof(struct node)); new->data=val;
if(head==NULL){ new->prev=NULL; new->next=NULL; head = new; } else{ new->prev=NULL; new->next=head; head->prev=new; head = new; } }

In this program, we are doing following things:

  1. Creating a structure for node, which contains a value and two pointer. 
  2. After this we are checking if the head is empty so make the new node head.
  3. If the head is not empty then make the new node previous pointer null and next pointer points to head and make the head prev node points to next of new node.
  4. After this make the new node as head.
  5. This is how we insert at the beginning.

So this is how the function is working.

#include<stdio.h>
#include<stdlib.h>

struct node{
    struct node *prev;
    int data;
    struct node *next;
};
struct node *head = NULL;

void insertElementAtBeginning(int val){
struct node *new = malloc(sizeof(struct node));
new->data=val;
    
    if(head==NULL){
        new->prev=NULL;
        new->next=NULL;
        head = new;
    }
    else{
        new->prev=NULL;
        new->next=head;
        head->prev=new;
        head = new;
    }
    
}


void print()
{
    struct node *temp = head;

    while(temp != NULL)
    {
         printf("%d ", temp->data);
         temp = temp->next;
    }
}

int main()
{

     insertElementAtBeginning(1);
     insertElementAtBeginning(2);
     insertElementAtBeginning(3);
     print();

     return 0;
}
Load comments