Insertion in a Doubly Linked List (DLL)

                                Insertion in a Doubly Linked List (DLL)


A Doubly Linked List (DLL) is a linked list where each node has two pointers:

  • prev → Points to the previous node.
  • next → Points to the next node.

Types of Insertions in DLL

1️⃣ Insert at the Beginning
2️⃣ Insert at the End
3️⃣ Insert at a Specific Position


1️⃣ Insert at the Beginning

Steps:

  1. Create a new node.
  2. Set newNode.next = head (point new node to old head).
  3. Set head.prev = newNode (update old head's previous).
  4. Update head = newNode.

Code:

class DoublyLinkedList {
    class Node {
        int data;
        Node prev, next;
        Node(int data) {
            this.data = data;
            this.prev = this.next = null;
        }
    }

    Node head; // Head of DLL

    void insertAtBeginning(int data) {
        Node newNode = new Node(data);
        if (head != null) {
            newNode.next = head;
            head.prev = newNode;
        }
        head = newNode; // Update head
    }

    void display() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ⇄ ");
            temp = temp.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        DoublyLinkedList dll = new DoublyLinkedList();
        dll.insertAtBeginning(10);
        dll.insertAtBeginning(20);
        dll.insertAtBeginning(30);
        dll.display();  // Output: 30 ⇄ 20 ⇄ 10 ⇄ null
    }
}

2️⃣ Insert at the End

Steps:

  1. Create a new node.
  2. Traverse to the last node.
  3. Update last.next = newNode.
  4. Set newNode.prev = last.
void insertAtEnd(int data) {
    Node newNode = new Node(data);
    if (head == null) {
        head = newNode;
        return;
    }
    Node temp = head;
    while (temp.next != null) {
        temp = temp.next;
    }
    temp.next = newNode;
    newNode.prev = temp;
}


3️⃣ Insert at a Specific Position

Steps:

  1. Traverse to position pos-1.
  2. Insert new node between prevNode and nextNode.
  3. Update all pointers.

Code:


void insertAtPosition(int data, int pos) {
    Node newNode = new Node(data);
    if (pos == 1) {
        insertAtBeginning(data);
        return;
    }

    Node temp = head;
    for (int i = 1; temp != null && i < pos - 1; i++) {
        temp = temp.next;
    }
    
    if (temp == null) return; // Position out of bounds

    newNode.next = temp.next;
    if (temp.next != null) {
        temp.next.prev = newNode;
    }
    temp.next = newNode;
    newNode.prev = temp;
}

Example Execution

DoublyLinkedList dll = new DoublyLinkedList();
dll.insertAtEnd(10);
dll.insertAtEnd(20);
dll.insertAtEnd(30);
dll.insertAtPosition(25, 3);
dll.display(); // Output: 10 ⇄ 20 ⇄ 25 ⇄ 30 ⇄ null

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence