GeeksforGeeks App
Open App
Browser
Continue

# Delete every Kth node from circular linked list

Delete every kth node from a circular linked list until only one node is left. Also, print the intermediate lists.

Examples:

Input : n=4, k=2, list = 1->2->3->4
Output :
1->2->3->4->1
1->2->4->1
2->4->2
2->2

Input : n=9, k=4, list = 1->2->3->4->5->6->7->8->9
Output :
1->2->3->4->5->6->7->8->9->1
1->2->3->4->6->7->8->9->1
1->2->3->4->6->7->8->1
1->2->3->6->7->8->1
2->3->6->7->8->2
2->3->6->8->2
2->3->8->2
2->3->2
2->2

Algorithm:

Repeat the following steps until there is only one node left in the list.

• Case 1: The list is empty.
If the list is empty, simply return it.
• Case 2: The list has only one node.
If the list has only one node left, we will print the list and return it as our goal is reached.
• Case 3: The list has more than one node.
Define two pointers curr and prev and initialize the pointer curr with the head node.

Traverse the list using curr pointer by iterating it k times.

• The node to be deleted is the first node of the list.
If yes, then move prev until it reaches the last node. After prev reaches the last node, set head = head -> next and prev -> next = head. Delete curr.
• The node to be deleted is the last node in the list.
The condition to check this is (curr -> next == head).
If curr is the last node. Set prev -> next = head and delete the node curr for free(curr).
• The one to be deleted is neither the first node nor the last node, then set prev -> next = temp -> next and delete curr.

Implementation:

## Javascript



Output

1->2->3->4->5->6->7->8->9->1
1->2->3->4->6->7->8->9->1
1->2->3->4->6->7->8->1
1->2->3->6->7->8->1
2->3->6->7->8->2
2->3->6->8->2
2->3->8->2
2->3->2
2->2

Complexity Analysis:

• Time Complexity: O(n*n), as we are using nested loops to traverse n*n times. for deleting and printing the linked list. Where n is the number of nodes in the linked list.
• Auxiliary Space: O(1), as we are not using any extra space.

My Personal Notes arrow_drop_up