Insert Node at the beginning of the Doubly Linked List

Hello Coders! Welcome to nkcoderz blog, 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 Node at the beginning of the Doubly Linked List

How To Insert 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;
}

If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment