700297. Remove every k'th node
Remove every k'th node
Summary
The problem is to remove every kth node from a singly linked list. This involves skipping nodes at intervals of k, effectively removing them from the original list. The key concept involved is manipulating a linked list, specifically removing nodes while traversing the list.
Detailed Explanation
To solve this problem, we'll create a new pointer that moves one step ahead every kth node. As we traverse the original list, we'll keep track of the current node and remove it if it's the kth node. We'll also maintain a reference to the previous node to correctly update the next pointer.
Here's a step-by-step breakdown of the solution:
- Initialize three pointers:
curr,prev, andkth. - Set
kthto0andcurrto the head of the linked list. - Traverse the linked list:
- If
kthis equal to0, it means we've reached a node that should be removed.- Update
prevto point to the current node (curr). - Move
kthto(kth + 1) % k. This ensures we skip nodes at intervals ofk.
- Update
- Otherwise, move
currone step ahead and updatekthto(kth + 1) % k.
- If
- Repeat steps 3 until the end of the linked list is reached.
- Update the next pointer of the last node (
prev) to point toNULL, effectively terminating the list.
Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a few extra variables to store the pointers and counters.
Optimized Solutions
Java
public class RemoveEveryKthNode {
public static void removeEveryKthNode(ListNode head, int k) {
ListNode prev = null;
ListNode curr = head;
int count = 0;
while (curr != null) {
if ((count + 1) % k == 0) {
prev = curr;
curr = curr.next;
continue;
}
prev = curr;
curr = curr.next;
count++;
}
}
}