#369Medium#17 in Palo Alto Networks's list· asked at 2 companies
Deletion of the head of LL
Problem
Given the head of a singly linked list, delete the first node and return the new head. Return null if the list is empty or becomes empty.
Input / Output
- Input: head of a singly linked list.
- Output: head after deleting the first node.
Examples
Example 1
Input: 1 -> 2 -> 3
Output: 2 -> 3
Example 2
Input: 5
Output: empty
Example 3 Input: empty Output: empty
Constraints
0 <= number of nodes <= 10^5
Approach
- If
headisnull, returnnull. newHead = head.next.- Detach the old head (
head.next = null) so the memory can be reclaimed, and returnnewHead.
Deleting the head is O(1) because a linked list has no need to shift elements — contrast with deleting index 0 of an array, which is O(n). This is the property that makes linked lists suitable for queues and LRU caches.
In languages with manual memory management (C/C++), free/delete the old node after re-pointing.
Complexity
- Time: O(1)
- Space: O(1)
Reference solution (Python)
class ListNode:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def delete_head(head):
if head is None:
return None
new_head = head.next
head.next = None
return new_head
Test cases
| Input | Expected |
|---|---|
1->2->3 | 2->3 |
5 | None |
| empty | None |
1->1 | 1 |