Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.
Input : 1->2->3->4->5->6->7->8 k = 3 Output : 1->2->4->5->7->8 As 3 is the k-th node after its deletion list would be 1->2->4->5->6->7->8 And now 4 is the starting node then from it, 6 would be the k-th node. So no other kth node could be there.So, final list is: 1->2->4->5->7->8. Input: 1->2->3->4->5->6 k = 1 Output: Empty list All nodes need to be deleted
The idea is traverse the list from beginning and keep track of nodes visited after last deletion. Whenever count becomes k, delete current node and reset count as 0.
(1) Traverse list and do following (a) Count node before deletion. (b) If (count == k) that means current node is to be deleted. (i) Delete current node i.e. do // assign address of next node of // current node to the previous node // of the current node. prev->next = ptr->next i.e. (ii) Reset count as 0, i.e., do count = 0. (c) Update prev node if count != 0 and if count is 0 that means that node is a starting point. (d) Update ptr and continue until all k-th node gets deleted.
Below is C++ implementation.
1 2 4 5 7 8
Time Complexity : O(n)
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Remove first node of the linked list
- Remove last node of the linked list
- Create new linked list from two given linked list with greater element at each node
- Swap Kth node from beginning with Kth node from end in a Linked List
- Linked List | Set 2 (Inserting a node)
- Program for n'th node from the end of a Linked List
- Linked List | Set 3 (Deleting a node)
- Squareroot(n)-th node in a Linked List
- Delete Nth node from the end of the given linked list
- Find the balanced node in a Linked List
- Find the fractional (or n/k - th) node in linked list
- Reverse each word in a linked list node
- Sum of nodes in a linked list which are greater than next node
- Delete every Kth node from circular linked list
- Find modular node in a linked list