![]() |
VOOZH | about |
Given a singly linked list, the task is to remove every kth node of the linked list. Assume that k is always less than or equal to the length of the Linked List.
Examples :
Input: LinkedList: 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 2
Output: 1 -> 3 -> 5
Explanation: After removing every 2nd node of the linked list, the resultant linked list will be: 1 -> 3 -> 5 .Input: LinkedList: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10, k = 3
Output: 1 -> 2 -> 4 -> 5 -> 7 -> 8 -> 10
Explanation: After removing every 3rd node of the linked list, the resultant linked list will be: 1 -> 2 -> 4 -> 5 -> 7 -> 8 -> 10.
The idea is to traverse the linked list while maintaining a counter to track node positions. Every time the counter reaches k, update the next pointer of the previous node to skip the current kth node, effectively removing it from the list. Continue this process until reaching the end of the list. This method ensures that the kthnodes are removed as required while preserving the rest of the list structure.
Below is the implementation of the above approach:
1 3 5
Time Complexity : O(n), where n is the number of nodes.
Auxiliary Space : O(1)