Insert node before head in Doubly Linked List
Pattern: Doubly and circular lists
Make a node whose next is the old head, point the old head's prev back at it, and return the new node as the head.
The problem
Given the head of a doubly linked list and a value X, insert a new node holding X before the head and return the new
head. For example, 1 ⇄ 2 ⇄ 3 with X = 3 becomes 3 ⇄ 1 ⇄ 2 ⇄ 3.
The function name insertBeforeHead matches the takeUforward practice page. Use the link above for the exact
statement and limits. In this guide's code the node type is DNode.
Think first
- Which two links connect the new node and the old head?
- Is any walk needed?
- What should the new node's
prevbe?
Hints
Brute force, and why it fails
Rebuilding is O(n). Two links make it O(1).
The key insight
Inserting at the front is O(1) in both kinds of list; the doubly linked version adds the one back link.
Dry run
10
21
32
The list is 1 ⇄ 2 ⇄ 3 and X = 3.
Step 1 of 3
The plan
node = new DNode(X)
node.next = head
if head is not null: head.prev = node
return node
Complexity
- Time
O(1)- Space
O(1)
One node and two links.
Edge cases
- One node: two nodes.
- Empty list: just the new node.
- Equal values are fine.
I've built my logic, show the code
Java
class Solution {
public DNode insertBeforeHead(DNode head, int X) {
DNode node = new DNode(X);
node.next = head;
if (head != null) head.prev = node; // the old head now has something before it
return node;
}
}C++
class Solution {
public:
DNode* insertBeforeHead(DNode* head, int X) {
DNode* node = new DNode(X);
node->next = head;
if (head != NULL) head->prev = node; // the old head now has something before it
return node;
}
};Python
from lib import DNode
class Solution:
def insertBeforeHead(self, head: DNode, X: int) -> DNode:
node = DNode(X, None, head)
if head is not None:
head.prev = node # the old head now has something before it
return nodeCommon mistakes
- Forgetting
head.prev = node. - Returning the old head.
- Setting the new node's
prevto the head, which creates a loop.