VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-every-k-th-node-linked-list/

⇱ Remove every k-th node of the linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove every k-th node of the linked list

Last Updated : 16 Sep, 2024

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.

[Expected Approach - 1] Iterative Approach - O(n) Time and O(1) Space

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:


Output
1 3 5 

Time Complexity : O(n), where n is the number of nodes.
Auxiliary Space : O(1)

Comment
Article Tags: