Insert A Node in the Doubly Linked List

Before start discussing on “Insert a node in the doubly linked list?” First, I will put a light on a “singly linked list”, A singly linked list is a collection of nodes in which a node consists of a data part and pointer part. The data part store the value (maybe integer, character, and floating etc.) and pointer part store the address of the next node (as shown in image mention below).

doubly linked list

 

You can read this article, Pointer in C

Doubly linked list traversed in the forward and backward direction. A doubly linked list consists of a data part and two pointers (next and previous) in which one pointer store the address of the next node and another one store the address of the previous node.

double linked list

 

Insertion operation in the doubly linked list has been done in various ways:

1. Insert a node at the beginning.
2. Insert a node after a node.
3. Insert a node at the end.

You can also see how to insert a node in a single linked list, check the article

Generic linked list in C

Insert a node at the front

An algorithm to insert a node at the front of the doubly linked list.

Step1:

Create a HEAD pointer which points to the first node of the linked list.

Step2:

Create a new node TEMP and assign the value.

linked list

STEP3:

 

Then, move the address of the new node TEMP into HEAD.

 

then, TEMP node next pointer stores the value of the HEAD (Address of the first node) and HEAD pointer stores the address of the TEMP.

 

double linked list in c

 

C Program to insert a node at the front in the doubly linked list

In the below program, I am inserting a few nodes at the beginning of the doubly linked list.

 

 

Insert a node after a node in the doubly linked list

 

Step1: Calculate the length of the doubly linked list

Step2: Create a new node TEMP.

Step3: Enter a location and move head pointer until it reaches the desired location.

 

See an example,

In below example, I am inserting the node after the given position.

 

doubly linked list

 

Insert a node at the end of the doubly linked list

An algorithm to insert a node at the end of the linked list.

Step1:
Create a HEAD pointer which points to the first node of the linked list.

Step2:
Create a new node TEMP.

 

STEP3:

 

 

doubly linked list



Leave a Reply