Deletion of the head of LL
EasyReturn the second node
Problem
Given the head of a singly linked list, delete the head of the linked list and return the head of the modified list. The head is the first node of the linked list. Note : Please note that this section might seem a bit difficult without prior knowledge on what linkedList is, we will soon try to add basics concepts for your ease! If you know the concepts already please go ahead to give a shot to the problem. Cheers!
Just move the 'head' label to the second node.
The idea
Deleting the head is simply making head.next the new head — the old node becomes unreachable. The only thing to guard is an already-empty list.
The trick
- Return null when the list is empty rather than dereferencing.
- O(1); in a manual-memory language, free the old node after unlinking.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — linkedList = [1, 2, 3] Values: 1, 2, 3.
1if head == null: return null2head = head.next3return headInput
- array
- [1, 2, 3]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- linkedList = [1, 2, 3]
- Output:
- [2, 3]
- Explanation:
- The first node was removed.
Example 2
- Input:
- linkedList = [1]
- Output:
- []
- Explanation:
- Note that the head of the linked list gets changed.
Constraints
- 1 <= number of nodes in the Linked List <= 1000
- 0 <= ListNode.data<= 100
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.