Course contentsShow
← Computer Science
Lesson 341 of 2,8728. Linked Data StructuresFree lesson

Inserting at the Head of a Doubly Linked List

Adding a new node at the front while maintaining both forward and backward links correctly.

Inserting at the Head of a Doubly Linked List

What you'll learn: You'll learn how to add a new node at the front of a doubly linked list while correctly managing both forward and backward pointer connections.

The Core Challenge

Unlike singly linked lists where you only update one "next" pointer, inserting at the head of a doubly linked list requires managing two directions: the next pointer (forward) and the prev pointer (backward). Both the new node and the existing head need their pointers updated correctly.

The Step-by-Step Process

Think of it like inserting yourself at the front of a line where everyone holds hands with both neighbors:

  1. Create the new node with your data
  2. Point the new node's next to the current head
  3. Set the new node's prev to NULL (it's now the first node)
  4. If the list isn't empty, update the old head's prev to point back to the new node
  5. Update the head pointer to point to the new node

Why Order Matters

You must update the old head's prev pointer before moving the head pointer. Otherwise, you'd lose access to that node temporarily. It's like telling the person at the front "there's now someone before you" before you officially declare the new leader.

Empty List Edge Case

If the list is empty (head is NULL), steps 2-4 simplify: the new node's next and prev both point to NULL, and it becomes the head.

Key Takeaway: Inserting at the head of a doubly linked list requires updating four pointers—two in the new node (next and prev) and two connecting it to the existing structure—while carefully handling the empty list case.