Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Doubly Linked List Implementation in C and Java: A Comprehensive Guide

By Mukesh Kumar

Updated on Mar 20, 2025 | 21 min read | 1.3k views

Share:

Doubly Linked Lists are a key data structure in computer science, helping solve problems that require efficient insertion and deletion operations. Unlike singly linked lists, a doubly linked list allows traversal in both directions, making it more versatile in scenarios where both forward and backward navigation are needed.

For example, web browsers use doubly linked lists to navigate through history, allowing users to move both forwards and backwards through the pages they've visited. Similarly, multimedia applications use this data structure to manage playlists, where you can move seamlessly through songs in both directions.

In this blog, you’ll learn Doubly Linked List implementation in both C and Java. You’ll explore its core operations, practical examples, and the advantages of using this structure in real-world applications.

Understanding the Doubly Linked List Implementation: How Does It Really Work?

doubly linked list is a type of linked list where each node contains three parts: the data, a pointer to the next node, and a pointer to the previous node. 

Here are its key features:

  • Each node holds the actual data you want to store (like a number or a string).
  • The next pointer points to the next node in the list.
  • The prev pointer points to the previous node, which makes it different from a singly linked list, where nodes only point to the next node.

This structure enables bidirectional traversal, allowing you to move through the list from both ends.

Here are some core operations that you can perform using doubly linked list:

1. Traversing a Doubly Linked List: Traversing a doubly linked list is simple. You start at the head node and move forward using the next pointer. Want to go backward? Start at the tail and use the prev pointer. This bidirectional navigation makes it easier to explore data in both directions.

Imagine you have the following doubly linked list:

Head <-> 10 <-> 20 <-> 30 <-> Tail

Forward Traversal: Start at the head (10). Follow the next pointers:

  • First node: 10 → Next node: 20 → Next node: 30
  • End at the tail.

Backward Traversal: Start at the tail (30). Follow the prev pointers:

  • First node: 30 ← Previous node: 20 ← Previous node: 10
  • End at the head.

You can easily move through the list in both directions using the next and prev pointers.

2. Finding the Length of a Doubly Linked List: Counting the number of nodes in a doubly linked list is straightforward. You start at the head and traverse through each node, counting as you go. Since there’s no skipping, every node gets counted until you hit the end of the list.

Let’s say the doubly linked list is:

Head <-> 5 <-> 10 <-> 15 <-> Tail

To find the length, start at the head and count each node as you go through the list:

  • Start at head (5), count it as 1.
  • Move to the next node (10), count it as 2.
  • Move to the next node (15), count it as 3.
  • End at the tail.

So, the length of the list is 3. You’ve visited 3 nodes in total.

3. Inserting and Deleting Nodes: Insertion is quick! You can insert at the beginning, the end, or in the middle. When inserting in the middle, you only need to adjust the prev and next pointers of the neighboring nodes. Deleting nodes works similarly. Just make sure to update the surrounding nodes' pointers when removing a node to keep the list intact.

Imagine you have this list:

Head <-> 10 <-> 20 <-> Tail

Now, you want to insert 5 at the beginning:

  • Create a new node for 5.
  • Set its next pointer to the current head (10).
  • Set the prev pointer of the current head (10) to the new node (5).
  • Update the head to point to the new node (5).

After insertion:

Head <-> 5 <-> 10 <-> 20 <-> Tail

Now, let's delete the last node (20):

  • Start at the head and find the last node.
  • Set the prev pointer of the tail (20) to null.
  • Update the tail to the previous node (10).

After deletion:

Head <-> 5 <-> 10 <-> Tail

4. Handling Edge Cases: If the list is empty, the head and tail pointers are null, meaning there’s nothing to traverse. If there’s just one node and it’s deleted, both the head and tail become null. It’s crucial to handle this to avoid any dangling references.

An empty list looks like this:

Head -> null
Tail -> null

In this case, there are no nodes to traverse or manipulate. Both the head and tail are null.

Consider this list with just one node:

Head <-> 10 <-> Tail

If you delete the node:

  • Set both head and tail to null because there are no more nodes.
  • The list is now empty:
Head -> null
Tail -> null

These simple examples should make it clearer how the core operations work in a doubly linked list.

With these core operations, a doubly linked list becomes an efficient and flexible data structure, offering more functionality than a singly linked list while requiring just a bit more memory for the extra pointer.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

When working with data structures like doubly linked lists, it’s crucial to understand how to efficiently manage memory and operations. upGrad’s online Software Development courses can help you master data structure concepts, including linked lists, and equip you with the skills to tackle real-world programming challenges.

Also Read: What are Data Structures & Algorithm

Now that you understand the basic principles of a doubly linked list implementation, let’s dive into how to implement it in C.

Step-by-Step Guide to Generate a Doubly Linked List in C 

Implementing a doubly linked list in C offers deep insights into low-level memory management. In C, you manually allocate and deallocate memory using malloc and free, providing you with fine-grained control over resource usage and performance. 

Unlike Java, which relies on garbage collection, C requires explicit management of both next and prev pointers. While Java simplifies memory handling, it introduces overhead due to garbage collection, which may not always be ideal for high-performance or real-time systems. 

This hands-on approach in C allows for better control over memory and is why C is preferred in systems programming and embedded systems.

Step 1: Creating the Node Structure

A doubly linked list node holds three components: data, next pointer, and prev pointer. Here’s how you define it in C:

struct Node {
    int data;            // Data stored in the node
    struct Node* next;   // Pointer to the next node
    struct Node* prev;   // Pointer to the previous node
};

Step 2: Building the List: Insertion

Now, let’s go over how to insert nodes at the beginning, end, and specific position in the list.

To insert a node at the beginning, you:

  • Allocate memory for the new node.
  • Set the new node’s next pointer to the current head.
  • Set the current head’s prev pointer to the new node.
  • Update the head to point to the new node.
void insertAtBeginning(struct Node** head, int newData) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = newData;
    newNode->next = *head;
    newNode->prev = NULL;

    if (*head != NULL) {
        (*head)->prev = newNode;
    }

    *head = newNode;
}

For insertion at the end:

  • Traverse the list to find the last node.
  • Set the last node’s next pointer to the new node.
  • Set the new node’s prev pointer to the last node.
  • The new node’s next pointer is set to NULL.
void insertAtEnd(struct Node** head, int newData) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    struct Node* last = *head;
    newNode->data = newData;
    newNode->next = NULL;

    if (*head == NULL) {
        newNode->prev = NULL;
        *head = newNode;
        return;
    }

    while (last->next != NULL) {
        last = last->next;
    }

    last->next = newNode;
    newNode->prev = last;
}

To insert at a given position:

  • Traverse the list to reach the node before the specified position.
  • Update the next and prev pointers accordingly.
void insertAtPosition(struct Node** head, int newData, int position) {
    if (position == 0) {
        insertAtBeginning(head, newData);
        return;
    }

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    struct Node* temp = *head;
    newNode->data = newData;

    for (int i = 0; temp != NULL && i < position - 1; i++) {
        temp = temp->next;
    }

    if (temp == NULL) {
        printf("Position out of bounds\n");
        return;
    }

    newNode->next = temp->next;
    newNode->prev = temp;
    if (temp->next != NULL) {
        temp->next->prev = newNode;
    }
    temp->next = newNode;
}

Step 3: Displaying the List: Traversing and Printing

After inserting nodes, you can traverse and print the list. We’ll show both forward and backward traversal.

The forward traversal prints the list starting from the head, moving to the next node until the end.

void displayForward(struct Node* head) {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d <-> ", temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
}

For backward traversal, start at the tail of the list and move backward using the prev pointers.

void displayBackward(struct Node* head) {
    if (head == NULL) return;

    struct Node* temp = head;
    while (temp->next != NULL) {
        temp = temp->next;
    }

    while (temp != NULL) {
        printf("%d <-> ", temp->data);
        temp = temp->prev;
    }
    printf("NULL\n");
}

Step 4: Deleting Nodes

Deleting nodes involves updating the surrounding nodes' pointers to maintain the list integrity.

This function deletes the first node and updates the head:

void deleteFromBeginning(struct Node** head) {
    if (*head == NULL) return;

    struct Node* temp = *head;
    *head = (*head)->next;

    if (*head != NULL) {
        (*head)->prev = NULL;
    }

    free(temp);
}

For deleting the last node:

  • Traverse to the last node.
  • Set the second last node’s next pointer to NULL.
void deleteFromEnd(struct Node** head) {
    if (*head == NULL) return;

    struct Node* last = *head;
    while (last->next != NULL) {
        last = last->next;
    }

    if (last->prev != NULL) {
        last->prev->next = NULL;
    } else {
        *head = NULL;
    }

    free(last);
}

Complete C Code Doubly Linked List Example

Here’s the full program combining all the above steps, demonstrating the doubly linked list operations.

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

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

// Function declarations
void insertAtBeginning(struct Node** head, int newData);
void insertAtEnd(struct Node** head, int newData);
void insertAtPosition(struct Node** head, int newData, int position);
void displayForward(struct Node* head);
void displayBackward(struct Node* head);
void deleteFromBeginning(struct Node** head);
void deleteFromEnd(struct Node** head);

int main() {
    struct Node* head = NULL;

    insertAtBeginning(&head, 10);
    insertAtEnd(&head, 20);
    insertAtPosition(&head, 15, 1);

    printf("List in Forward Order:\n");
    displayForward(head);

    printf("List in Backward Order:\n");
    displayBackward(head);

    deleteFromEnd(&head);

    printf("After Deleting from End:\n");
    displayForward(head);

    return 0;
}

Explanation: This program demonstrates how to insert nodes at the beginning, end, and specific positions. It also shows how to display the list both forwards and backwards and delete nodes from the end.

Expected Output:

List in Forward Order:
15 <-> 10 <-> 20 <-> NULL
List in Backward Order:
20 <-> 10 <-> 15 <-> NULL
After Deleting from End:
15 <-> 10 <-> NULL

By following these steps, you can easily implement a fully functional doubly linked list in C. The operations for insertion, traversal, and deletion provide flexibility and efficiency in managing a dynamic set of elements.

Also Read: 29 C Programming Projects to Try in 2025 With Source Code

With a solid understanding of doubly linked list implementation in C, let’s now explore how to build a similar structure in Java. 

How to Create and Display a Doubly Linked List in Java? A Beginner’s Guide

Creating a Doubly Linked List in Java involves defining a node class with both forward and backward pointers, followed by building a linked list class to handle insertion, deletion, and traversal. 

Unlike C, Java simplifies memory management through garbage collection, freeing developers from manual memory allocation. However, this can introduce performance overhead, particularly in real-time systems, where fine-grained control over memory is crucial. 

Despite this, Java's object-oriented structure makes it easier to implement and maintain complex data structures like linked lists.

Let’s go through the steps to build and display a doubly linked list in Java.

Step 1: Defining the Node Class

First, you need to define the Node class. Here’s how you can define the Node class in Java:

class Node {
    int data;
    Node next;
    Node prev;

    // Constructor to create a new node
    public Node(int data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

The Node class has three components: data, next, and prev. The constructor initializes the data of the node and sets both the next and prev pointers to null.

Step 2: Setting Up the DoublyLinkedList Class

After defining the Node class, you can now move on to creating the DoublyLinkedList class to manage the nodes. This class will contain the following methods:

  • Insert: Insert nodes at the beginning, end, or a specific position.
  • Delete: Remove nodes from the beginning, end, or a specific position.
  • Display: Traverse the list and display the elements in both forward and backward directions.
class DoublyLinkedList {
    Node head;  // Head of the list

    // Constructor to create an empty list
    public DoublyLinkedList() {
        this.head = null;
    }
}

The DoublyLinkedList class has a head pointer to the first node in the list. Initially, it’s set to null.

Step 3: Implementing Insertion and Deletion

Now, let’s implement the methods to insert and delete nodes in the list. This includes:

  • Inserting at the beginning.
  • Inserting at the end.
  • Inserting at a specific position.
  • Deleting from the beginning and end.

Insertion at the Beginning:

public void insertAtBeginning(int data) {
    Node newNode = new Node(data);
    newNode.next = head;  // Link new node to the current head
    if (head != null) {
        head.prev = newNode;  // Set prev pointer of the old head to the new node
    }
    head = newNode;  // Move head to point to the new node
}

This method inserts a node at the beginning by adjusting the head pointer and linking the new node to the current head.

Insertion at the End:

public void insertAtEnd(int data) {
    Node newNode = new Node(data);
    if (head == null) {
        head = newNode;  // If the list is empty, make the new node the head
        return;
    }
    Node last = head;
    while (last.next != null) {
        last = last.next;  // Traverse to the last node
    }
    last.next = newNode;
    newNode.prev = last;  // Set prev of new node to the last node
}

If the list is empty, the new node becomes the head. Otherwise, we traverse to the last node and link it to the new node.

Insertion at a Specific Position:

public void insertAtPosition(int data, int position) {
    if (position == 0) {
        insertAtBeginning(data);
        return;
    }

    Node newNode = new Node(data);
    Node temp = head;

    for (int i = 0; temp != null && i < position - 1; i++) {
        temp = temp.next;  // Traverse to the node before the desired position
    }

    if (temp == null) {
        System.out.println("Position out of bounds");
        return;
    }

    newNode.next = temp.next;  // Link the new node to the next node
    newNode.prev = temp;  // Link the new node to the previous node

    if (temp.next != null) {
        temp.next.prev = newNode;  // Update the previous pointer of the next node
    }

    temp.next = newNode;  // Update the next pointer of the previous node
}

If the position is 0, it calls the insertAtBeginning method. Otherwise, it traverses to the node before the desired position and adjusts the pointers to insert the new node.

Deletion from the Beginning:

public void deleteFromBeginning() {
    if (head == null) return;  // If the list is empty, do nothing

    head = head.next;  // Move the head pointer to the next node
    if (head != null) {
        head.prev = null;  // Set the previous pointer of the new head to null
    }
}

This method removes the first node by updating the head pointer to point to the next node and adjusting the prev pointer of the new head.

Deletion from the End:

public void deleteFromEnd() {
    if (head == null) return;  // If the list is empty, do nothing

    Node last = head;
    while (last.next != null) {
        last = last.next;  // Traverse to the last node
    }

    if (last.prev != null) {
        last.prev.next = null;  // Set the next pointer of the second last node to null
    } else {
        head = null;  // If the list has only one node, set head to null
    }
}

This method traverses the list to find the last node and removes it by adjusting the next pointer of the second-last node.

Step 4: Traversal and Display

Let’s implement methods to traverse and display the list forward and backward.

Forward Traversal: 

public void displayForward() {
    Node temp = head;
    while (temp != null) {
        System.out.print(temp.data + " <-> ");
        temp = temp.next;
    }
    System.out.println("NULL");
}

This method starts at the head and moves forward through the list, printing the data of each node.

Backward Traversal:

public void displayBackward() {
    if (head == null) return;  // If the list is empty, do nothing

    Node temp = head;
    while (temp.next != null) {
        temp = temp.next;  // Traverse to the last node
    }

    while (temp != null) {
        System.out.print(temp.data + " <-> ");
        temp = temp.prev;  // Move to the previous node
    }
    System.out.println("NULL");
}

This method traverses the list backward, starting at the tail and moving to the previous node.

Complete Java Code Doubly Linked List Example

Now, let’s put everything together with a complete Java example that demonstrates how to build and manipulate a doubly linked list:

class Node {
    int data;
    Node next;
    Node prev;

    public Node(int data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

class DoublyLinkedList {
    Node head;

    public DoublyLinkedList() {
        this.head = null;
    }

    // Insert methods (insert at beginning, end, position)
    public void insertAtBeginning(int data) { /* ... */ }
    public void insertAtEnd(int data) { /* ... */ }
    public void insertAtPosition(int data, int position) { /* ... */ }

    // Delete methods (delete from beginning, end)
    public void deleteFromBeginning() { /* ... */ }
    public void deleteFromEnd() { /* ... */ }

    // Display methods (forward and backward)
    public void displayForward() { /* ... */ }
    public void displayBackward() { /* ... */ }

    public static void main(String[] args) {
        DoublyLinkedList list = new DoublyLinkedList();

        // Inserting nodes
        list.insertAtBeginning(10);
        list.insertAtEnd(20);
        list.insertAtPosition(15, 1);

        System.out.println("List in Forward Order:");
        list.displayForward();

        System.out.println("List in Backward Order:");
        list.displayBackward();

        // Deleting from the end
        list.deleteFromEnd();
        System.out.println("After Deleting from End:");
        list.displayForward();
    }
}

In this Java implementation of a Doubly Linked List, the Node class contains data, next, and prev references. The DoublyLinkedList class handles insertion, deletion, and traversal, with Java using object references instead of manual pointers. The main method demonstrates these operations. 

Unlike C, Java handles memory management automatically through garbage collection, simplifying the implementation. This code highlights Java's object-oriented approach and memory management for creating a doubly linked list.

Expected Output:

List in Forward Order:
10 <-> 15 <-> 20 <-> NULL
List in Backward Order:
20 <-> 15 <-> 10 <-> NULL
After Deleting from End:
10 <-> 15 <-> NULL

By mastering these techniques, you’ll be well-equipped to implement and optimize doubly linked lists in your Java projects.

Also Read: Data Structures in Javascript Explained: Importance, Types & Advantages

With a clear understanding of Doubly Linked List implementation in Java, let’s dive deeper into how exactly it will benefit you as a programmer.

Why Choose a Doubly Linked List? Exploring Its Pros and Cons

A Doubly Linked List is a powerful data structure, but like any tool, it comes with its set of advantages and disadvantages. When deciding whether to use a doubly linked list, it's essential to weigh these factors and consider the specific use cases where this structure shines or falls short.

When to Use a Doubly Linked List:

  • When you need bidirectional traversal. This is helpful in applications like web browsers (forward and backward navigation) or music players (navigate both ways in a playlist).
  • When your operations require efficient deletion or insertion at both ends of the list.
  • In real-time applications where performance improvements in deletion or insertion are critical (e.g., memory management systems, cache management).

When Not to Use a Doubly Linked List:

  • When memory efficiency is a concern. If you don’t need bidirectional traversal, the additional prev pointer in each node adds unnecessary memory overhead.
  • When simpler data structures like singly linked lists can handle your needs. If you don’t require backward traversal or fast deletions from arbitrary positions, a singly linked list is more space-efficient and easier to implement.

Here’s a comparison of the pros and cons of a doubly linked list:

Advantages

Disadvantages

You can traverse the list both forwards and backwards. Requires extra space for the prev pointer.
Deleting a node is faster because you have access to both previous and next pointers. More complicated than singly linked lists, especially when handling edge cases (like empty or single-node lists).
Easier insertion at both ends and at specific positions in the list. Slightly slower than singly linked lists due to the increased number of pointers and extra memory overhead.

So, doubly linked lists offer powerful advantages in terms of flexibility and efficiency for certain operations. However, they come at the cost of increased memory usage and implementation complexity. 

Also Read: Data Structures & Algorithm in Python: Everything You Need to Know

Now that you know when to use Doubly Linked Lists, it’s time to dive into the real-world applications so you understand them better.

Exploring Real-World Applications with Doubly Linked List Examples

Doubly linked lists are powerful data structures that provide efficient bidirectional navigation, fast insertion, and deletion at both ends. These features make them ideal for situations where quick, flexible modifications to data are needed.

In real-world applications, doubly linked lists are often used in systems requiring dynamic memory management, history tracking, or efficient data traversal.

Let’s explore how this data structure is leveraged across different domains.

1. Music/Video Players (Playlist Management)

In media players like Spotify or VLC, doubly linked lists are used to manage playlists. This allows users to easily navigate through songs or videos, moving backwards and forwards in the playlist. 

For example, when a user clicks "next" or "previous," the player moves between nodes in the list, providing flexibility and efficient playback control. This structure is ideal for scenarios where bidirectional traversal is needed for smooth navigation.

2. Memory Management Systems

In older operating systems, doubly linked lists were employed in memory management to track free memory blocks in a heap. The structure allowed efficient allocation and deallocation by moving forward or backward through memory blocks. 

However, modern operating systems often use more advanced systems like buddy systems or free lists. These offer better performance and handle memory fragmentation more effectively, making doubly linked lists less common today.

3. Undo/Redo Functionality

In software like word processors or graphic design tools, doubly linked lists store a history of user actions, enabling efficient undo and redo operations. Each action is represented as a node in the list, allowing users to move back and forth through their history of changes. 

This bidirectional traversal ensures that users can easily navigate through edits, even in complex workflows with multiple steps.

4. Operating System Process Scheduling

In operating systems, doubly linked lists are used to manage process scheduling. Processes are stored as nodes, with the ability to quickly switch between them using forward and backward navigation. This allows OS schedulers to prioritize or pause tasks efficiently. 

For example, during multitasking, processes can be scheduled in a way that prioritizes critical tasks while allowing easy transitions to background tasks, all managed dynamically by the doubly linked list structure.

5. Job Scheduling in Real-Time Systems

In real-time systems, such as telecommunications or industrial machinery, doubly linked lists help manage tasks or jobs that need to be executed at specific intervals. The structure allows for efficient scheduling and rescheduling of tasks, where new jobs can be added or completed jobs can be removed by navigating through the list. 

This capability is crucial for systems that require precise timing and management of jobs in both directions.

6. Navigation Systems (GPS)

In GPS navigation systems, doubly linked lists are used to store routes and waypoints. As users navigate, the system allows for backward and forward navigation through waypoints, helping them adjust their path easily. 

If a user needs to retrace steps or take a different route, the doubly linked list allows for smooth transitions between previous and next points, ensuring efficient pathfinding.

7. Database Record Management

Doubly linked lists are used in database indices to store references to records, enabling efficient insertion, deletion, and bidirectional traversal of records. For example, in a transactional database, as new records are added, they can be quickly accessed or removed from any point in the list, improving query performance. 

This flexibility makes doubly linked lists ideal for databases with frequent updates and complex queries.

8. Browser Tab Management

Web browsers like Chrome or Firefox use doubly linked lists to manage open tabs. This allows users to efficiently switch between tabs and navigate back and forth through their browsing history. 

When users press the "back" or "forward" buttons, the browser uses the doubly linked list to traverse through the history of visited pages, making the browsing experience smoother and more responsive.

These unique applications show how doubly linked lists enable dynamic, efficient management of data where both forward and backward navigation or operations are key to system performance.

Also Read: 20 Most Popular Programming Languages in 2025

Now that you’re familiar with the Doubly Linked List implementation and usage, let’s explore how upGrad can take your learning journey forward. 

How Can upGrad Improve Your Knowledge of C and Java Programming?

With your strong foundation in Doubly Linked Lists, you’re ready to advance your programming skills with upGrad’s advanced courses. Learn advanced techniques in data structures, algorithms, and practical applications to accelerate your career in software development.

Through hands-on projects, you’ll apply these concepts to solve complex problems. You will be able to efficiently manage data structures like doubly linked lists and build high-performance applications.

Here are some relevant courses you can explore:

  • Java Object-oriented Programming
  • JavaScript Basics from Scratch
  • Master of Science in AI and Data Science
  • Best Full Stack Developer Bootcamp
  • Master of Design in User Experience

If you're unsure about the next step in your learning journey, you can contact upGrad’s personalized career counseling for guidance on choosing the best path tailored to your goals. You can also visit your nearest upGrad center and start hands-on training today!  

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. How does a doubly linked list improve performance in web browser history management?

2. Why is a doubly linked list preferred for managing playlists in music or video players?

3. What challenges do developers face when implementing undo/redo functionality using doubly linked lists?

4. How can doubly linked lists be used in operating system process scheduling?

5. What’s the advantage of using a doubly linked list for job scheduling in real-time systems?

6. Why might a doubly linked list be inefficient for smaller, static datasets?

7. How can a doubly linked list help with memory management in operating systems?

8. In database systems, how do doubly linked lists improve index management?

9. What performance issues might arise when using a doubly linked list in large-scale applications?

10. How are doubly linked lists useful in real-time data structures for navigation systems?

11. What are some limitations of using doubly linked lists in real-time applications?

Mukesh Kumar

138 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program

Suggested Blogs

blog-card

Uses of C Language - Its Relevance in 2025

C is a powerful, general-purpose programming language known for its speed, efficiency, and control over system resources. It forms the foundation of many modern languages like 

21 Mar 2025 | 11 min read

blog-card

Understanding and Implementing the Knapsack Problem (0/1)

The Knapsack Problem is a powerful optimization tool used to make the most of limited resources. For instance, in logistics and resource allocation, it helps businesses determine which items to prioritize. This could be packing a truck, budgeting for a project, or selecting investments—it ensures maximum value under strict constraints. 

20 Mar 2025 | 24 min read

blog-card

SQL Jobs for Freshers: Salary, Career Growth & Opportunities

Imagine data as a vast lake behind a dam. Just as an engineer carefully controls the flow of water to ensure optimal flow, an SQL developer manages the “vast lake” of data. They ensure that the data is stored safely and released at the right time so businesses can make informed decisions without being underprepared.  T

19 Mar 2025 | 14 min read

blog-card

Java Developer Salary: What to Expect in India 2025

Java developers play a crucial role in modern organizations by creating scalable and secure applications that power essential digital infrastructure. Their expertise is central to designing robust backend systems, optimizing code performance, and ensuring the reliability of software used by businesses worldwide. The importa

19 Mar 2025 | 6 min read