#361Easy· asked at 2 companies
Delete head of Doubly Linked List
Problem
Given the head of a doubly linked list, delete the head node and return the new head. Each node has val, prev and next. If the list is empty, return null. If it has a single node, the result is an empty list.
Input / Output
- Input: head of a DLL.
- Output: head of the list after removing the first node.
Examples
Example 1
Input: 1 <-> 2 <-> 3
Output: 2 <-> 3
Example 2
Input: 5
Output: empty list
Example 3 Input: empty list Output: empty list
Constraints
0 <= number of nodes <= 10^5
Approach
The head node is head; its successor is head.next.
- If
headisnull, returnnull. - Let
newHead = head.next. - If
newHeadis notnull, setnewHead.prev = null— this is the step people forget; leaving a danglingprevpointer breaks backward traversal. - Detach the old head (
head.next = null) so it can be garbage collected / freed, and returnnewHead.
The operation touches at most two nodes and runs in constant time regardless of list length — one of the reasons a doubly linked list is chosen over an array for queue-like structures.
Complexity
- Time: O(1)
- Space: O(1)
Reference solution (Python)
class Node:
def __init__(self, val):
self.val, self.prev, self.next = val, None, None
def delete_head(head):
if head is None:
return None
new_head = head.next
if new_head:
new_head.prev = None
head.next = None
return new_head
Test cases
| Input | Expected |
|---|---|
1<->2<->3 | 2<->3, and new_head.prev is None |
5 | None |
| empty | None |
1<->1 | 1 (second node) |