Deletion of the Kth element of Linked List
Problem
Given the head of a singly linked list and a 1-based position k, delete the k-th node and return the head of the modified list. If k exceeds the list length, return the list unchanged.
Input / Output
- Input: head, integer
k. - Output: head after deletion.
Examples
Example 1
Input: 1 -> 2 -> 3 -> 4, k = 3
Output: 1 -> 2 -> 4
Example 2
Input: 1 -> 2 -> 3, k = 1
Output: 2 -> 3
Example 3
Input: 1 -> 2, k = 2
Output: 1
Example 4
Input: 1 -> 2, k = 7
Output: 1 -> 2
Constraints
1 <= number of nodes <= 10^51 <= k <= 10^9
Approach
In a singly linked list you cannot step backwards, so to unlink node k you must hold a pointer to node k-1.
- If
k == 1, the answer is simplyhead.next(delete head). - Otherwise walk a pointer
prevk-2steps fromhead. Ifprevorprev.nextbecomesnullalong the way,kis out of range — returnhead. - Set
prev.next = prev.next.next.
A dummy node in front of head removes the special case: start prev at the dummy, walk k-1 steps, unlink, and return dummy.next. This trick is worth showing in interviews because it also simplifies "remove N-th from end", "delete duplicates", and most insertion problems.
Complexity
- Time: O(k)
- Space: O(1)
Reference solution (Python)
def delete_kth(head, k):
dummy = ListNode(0, head)
prev = dummy
for _ in range(k - 1):
if prev.next is None:
return head
prev = prev.next
if prev.next is None:
return head
prev.next = prev.next.next
return dummy.next
Test cases
| Input | Expected |
|---|---|
1->2->3->4, k=3 | 1->2->4 |
1->2->3, k=1 | 2->3 |
1->2, k=2 | 1 |
1->2, k=7 | 1->2 |