Delete head of Doubly Linked List
Pattern: Doubly and circular lists
The second node becomes the head. Clear its prev so nothing points back at the old head, and return it.
The problem
Given the head of a doubly linked list, delete the head and return the new head. A list with one node becomes empty.
For example, 1 ⇄ 2 ⇄ 3 becomes 2 ⇄ 3, and 7 becomes empty.
The function name deleteHead 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 node becomes the head?
- Which of its pointers still mentions the old head?
- What does one node give?
Hints
Brute force, and why it fails
Nothing is simpler: O(1).
The key insight
In a doubly linked list, removing the head has one extra duty compared with a singly linked list: the new head's prev
must become null.
Dry run
10
21
32
The list is 1 ⇄ 2 ⇄ 3. The head is 1.
Step 1 of 3
The plan
if head is null or head.next is null: return null
next = head.next
next.prev = null
head.next = null
return next
Complexity
- Time
O(1)- Space
O(1)
Two assignments.
Edge cases
- One node: empty.
- Two nodes: the second is left.
- Empty list: empty.
I've built my logic, show the code
Java
class Solution {
public DNode deleteHead(DNode head) {
if (head == null || head.next == null) return null; // zero or one node: nothing is left
DNode next = head.next;
next.prev = null; // the second node becomes the head
head.next = null;
return next;
}
}C++
class Solution {
public:
DNode* deleteHead(DNode* head) {
if (head == NULL || head->next == NULL) return NULL; // zero or one node: nothing is left
DNode* next = head->next;
next->prev = NULL; // the second node becomes the head
head->next = NULL;
return next;
}
};Python
from lib import DNode
class Solution:
def deleteHead(self, head: DNode) -> DNode:
if head is None or head.next is None:
return None # zero or one node: nothing is left
nxt = head.next
nxt.prev = None # the second node becomes the head
head.next = None
return nxtCommon mistakes
- Forgetting to clear the new head's
prev. - Returning
headinstead ofhead.next. - Not handling the single-node list.