Insert A Node At The End of A Doubly Linked List

Hello Coders! Welcome to nkcoderz blog. In this post, you will learn how to insert new node at the end of the Doubly Linked List, Code for the above task given below:

How To Insert A Node At The End of A Doubly Linked List

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

struct node *head = NULL;

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

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 prev NULL and the next also NULL.
  3. If the head is not empty then traverse and find the last node which is not NULL and make the new node prev point to last node and the new node next NULL.
  4. This is how we insert at the end.

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 insertAtEnd(int a){
struct node *new = malloc(sizeof(struct node));
new->data=a;
    
    if(head==NULL){
        new->prev=NULL;
        new->next=NULL;
        head = new;
    }
    else{
        struct node *temp = head;
        while(temp->next != NULL){
            temp=temp->next;
    }
        temp->next = new;
        new->prev = temp;
        new->next = NULL;
    }
}

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

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

int main()
{

     insertAtEnd(1);
     insertAtEnd(2);
     insertAtEnd(3);
     print();

     return 0;
}
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment