Delete every Kth node from circular linked list
Last Updated :
02 Sep, 2022
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.
Conditions to check this( curr == head && curr->next == head).
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:
C++
// C++ program to delete every kth Node from
// circular linked list.
#include <bits/stdc++.h>
using namespace std;
/* structure for a Node */
struct Node {
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
/*Utility function to print the circular linked list*/
void printList(Node* head)
{
if (head == NULL)
return;
Node* temp = head;
do {
cout << temp->data << "->";
temp = temp->next;
} while (temp != head);
cout << head->data << endl;
}
/*Function to delete every kth Node*/
void deleteK(Node** head_ref, int k)
{
Node* head = *head_ref;
// If list is empty, simply return.
if (head == NULL)
return;
// take two pointers - current and previous
Node *curr = head, *prev;
while (true) {
// Check if Node is the only Node\
// If yes, we reached the goal, therefore
// return.
if (curr->next == head && curr == head)
break;
// Print intermediate list.
printList(head);
// If more than one Node present in the list,
// Make previous pointer point to current
// Iterate current pointer k times,
// i.e. current Node is to be deleted.
for (int i = 0; i < k; i++) {
prev = curr;
curr = curr->next;
}
// If Node to be deleted is head
if (curr == head) {
prev = head;
while (prev->next != head)
prev = prev->next;
head = curr->next;
prev->next = head;
*head_ref = head;
free(curr);
}
// If Node to be deleted is last Node.
else if (curr->next == head) {
prev->next = head;
free(curr);
}
else {
prev->next = curr->next;
free(curr);
}
}
}
/* Function to insert a Node at the end of
a Circular linked list */
void insertNode(Node** head_ref, int x)
{
// Create a new Node
Node* head = *head_ref;
Node* temp = new Node(x);
// if the list is empty, make the new Node head
// Also, it will point to itself.
if (head == NULL) {
temp->next = temp;
*head_ref = temp;
}
// traverse the list to reach the last Node
// and insert the Node
else {
Node* temp1 = head;
while (temp1->next != head)
temp1 = temp1->next;
temp1->next = temp;
temp->next = head;
}
}
/* Driver program to test above functions */
int main()
{
// insert Nodes in the circular linked list
struct Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
insertNode(&head, 7);
insertNode(&head, 8);
insertNode(&head, 9);
int k = 4;
// Delete every kth Node from the
// circular linked list.
deleteK(&head, k);
return 0;
}
Java
// Java program to delete every kth Node from
// circular linked list.
class GFG
{
/* structure for a Node */
static class Node
{
int data;
Node next;
Node(int x)
{
data = x;
next = null;
}
};
/*Utility function to print
the circular linked list*/
static void printList(Node head)
{
if (head == null)
return;
Node temp = head;
do
{
System.out.print( temp.data + "->");
temp = temp.next;
}
while (temp != head);
System.out.println(head.data );
}
/*Function to delete every kth Node*/
static Node deleteK(Node head_ref, int k)
{
Node head = head_ref;
// If list is empty, simply return.
if (head == null)
return null;
// take two pointers - current and previous
Node curr = head, prev=null;
while (true)
{
// Check if Node is the only Node\
// If yes, we reached the goal, therefore
// return.
if (curr.next == head && curr == head)
break;
// Print intermediate list.
printList(head);
// If more than one Node present in the list,
// Make previous pointer point to current
// Iterate current pointer k times,
// i.e. current Node is to be deleted.
for (int i = 0; i < k; i++)
{
prev = curr;
curr = curr.next;
}
// If Node to be deleted is head
if (curr == head)
{
prev = head;
while (prev.next != head)
prev = prev.next;
head = curr.next;
prev.next = head;
head_ref = head;
}
// If Node to be deleted is last Node.
else if (curr.next == head)
{
prev.next = head;
}
else
{
prev.next = curr.next;
}
}
return head;
}
/* Function to insert a Node at the end of
a Circular linked list */
static Node insertNode(Node head_ref, int x)
{
// Create a new Node
Node head = head_ref;
Node temp = new Node(x);
// if the list is empty, make the new Node head
// Also, it will point to itself.
if (head == null)
{
temp.next = temp;
head_ref = temp;
return head_ref;
}
// traverse the list to reach the last Node
// and insert the Node
else
{
Node temp1 = head;
while (temp1.next != head)
temp1 = temp1.next;
temp1.next = temp;
temp.next = head;
}
return head;
}
/* Driver code */
public static void main(String args[])
{
// insert Nodes in the circular linked list
Node head = null;
head = insertNode(head, 1);
head = insertNode(head, 2);
head = insertNode(head, 3);
head = insertNode(head, 4);
head = insertNode(head, 5);
head = insertNode(head, 6);
head = insertNode(head, 7);
head = insertNode(head, 8);
head = insertNode(head, 9);
int k = 4;
// Delete every kth Node from the
// circular linked list.
head = deleteK(head, k);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 program to delete every kth Node from
# circular linked list.
import math
# structure for a Node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Utility function to print the circular linked list
def printList(head):
if (head == None):
return
temp = head
print(temp.data, end = "->")
temp = temp.next
while (temp != head):
print(temp.data, end = "->")
temp = temp.next
print(head.data)
# Function to delete every kth Node
def deleteK(head_ref, k):
head = head_ref
# If list is empty, simply return.
if (head == None):
return
# take two pointers - current and previous
curr = head
prev = None
while True:
# Check if Node is the only Node\
# If yes, we reached the goal, therefore
# return.
if (curr.next == head and curr == head):
break
# Print intermediate list.
printList(head)
# If more than one Node present in the list,
# Make previous pointer point to current
# Iterate current pointer k times,
# i.e. current Node is to be deleted.
for i in range(k):
prev = curr
curr = curr.next
# If Node to be deleted is head
if (curr == head):
prev = head
while (prev.next != head):
prev = prev.next
head = curr.next
prev.next = head
head_ref = head
# If Node to be deleted is last Node.
elif (curr.next == head) :
prev.next = head
else :
prev.next = curr.next
# Function to insert a Node at the end of
#a Circular linked list
def insertNode(head_ref, x):
# Create a new Node
head = head_ref
temp = Node(x)
# if the list is empty, make the new Node head
# Also, it will po to itself.
if (head == None):
temp.next = temp
head_ref = temp
return head_ref
# traverse the list to reach the last Node
# and insert the Node
else :
temp1 = head
while (temp1.next != head):
temp1 = temp1.next
temp1.next = temp
temp.next = head
return head
# Driver Code
if __name__=='__main__':
# insert Nodes in the circular linked list
head = None
head = insertNode(head, 1)
head = insertNode(head, 2)
head = insertNode(head, 3)
head = insertNode(head, 4)
head = insertNode(head, 5)
head = insertNode(head, 6)
head = insertNode(head, 7)
head = insertNode(head, 8)
head = insertNode(head, 9)
k = 4
# Delete every kth Node from the
# circular linked list.
deleteK(head, k)
# This code is contributed by Srathore
C#
// C# program to delete every kth Node from
// circular linked list.
using System;
class GFG
{
/* structure for a Node */
public class Node
{
public int data;
public Node next;
public Node(int x)
{
data = x;
next = null;
}
};
/*Utility function to print
the circular linked list*/
static void printList(Node head)
{
if (head == null)
return;
Node temp = head;
do
{
Console.Write( temp.data + "->");
temp = temp.next;
}
while (temp != head);
Console.WriteLine(head.data );
}
/*Function to delete every kth Node*/
static Node deleteK(Node head_ref, int k)
{
Node head = head_ref;
// If list is empty, simply return.
if (head == null)
return null;
// take two pointers - current and previous
Node curr = head, prev = null;
while (true)
{
// Check if Node is the only Node\
// If yes, we reached the goal, therefore
// return.
if (curr.next == head && curr == head)
break;
// Print intermediate list.
printList(head);
// If more than one Node present in the list,
// Make previous pointer point to current
// Iterate current pointer k times,
// i.e. current Node is to be deleted.
for (int i = 0; i < k; i++)
{
prev = curr;
curr = curr.next;
}
// If Node to be deleted is head
if (curr == head)
{
prev = head;
while (prev.next != head)
prev = prev.next;
head = curr.next;
prev.next = head;
head_ref = head;
}
// If Node to be deleted is last Node.
else if (curr.next == head)
{
prev.next = head;
}
else
{
prev.next = curr.next;
}
}
return head;
}
/* Function to insert a Node at the end of
a Circular linked list */
static Node insertNode(Node head_ref, int x)
{
// Create a new Node
Node head = head_ref;
Node temp = new Node(x);
// if the list is empty, make the new Node head
// Also, it will point to itself.
if (head == null)
{
temp.next = temp;
head_ref = temp;
return head_ref;
}
// traverse the list to reach the last Node
// and insert the Node
else
{
Node temp1 = head;
while (temp1.next != head)
temp1 = temp1.next;
temp1.next = temp;
temp.next = head;
}
return head;
}
/* Driver code */
public static void Main(String []args)
{
// insert Nodes in the circular linked list
Node head = null;
head = insertNode(head, 1);
head = insertNode(head, 2);
head = insertNode(head, 3);
head = insertNode(head, 4);
head = insertNode(head, 5);
head = insertNode(head, 6);
head = insertNode(head, 7);
head = insertNode(head, 8);
head = insertNode(head, 9);
int k = 4;
// Delete every kth Node from the
// circular linked list.
head = deleteK(head, k);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// javascript program to delete every kth Node from
// circular linked list. /* structure for a Node */
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
/*
* Utility function to print the circular linked list
*/
function printList(head) {
if (head == null)
return;
var temp = head;
do {
document.write(temp.data + "->");
temp = temp.next;
} while (temp != head);
document.write(head.data+"<br/>");
}
/* Function to delete every kth Node */
function deleteK(head_ref , k) {
var head = head_ref;
// If list is empty, simply return.
if (head == null)
return null;
// take two pointers - current and previous
var curr = head, prev = null;
while (true) {
// Check if Node is the only Node\
// If yes, we reached the goal, therefore
// return.
if (curr.next == head && curr == head)
break;
// Print intermediate list.
printList(head);
// If more than one Node present in the list,
// Make previous pointer point to current
// Iterate current pointer k times,
// i.e. current Node is to be deleted.
for (i = 0; i < k; i++) {
prev = curr;
curr = curr.next;
}
// If Node to be deleted is head
if (curr == head) {
prev = head;
while (prev.next != head)
prev = prev.next;
head = curr.next;
prev.next = head;
head_ref = head;
}
// If Node to be deleted is last Node.
else if (curr.next == head) {
prev.next = head;
} else {
prev.next = curr.next;
}
}
return head;
}
/*
* Function to insert a Node at the end of a Circular linked list
*/
function insertNode(head_ref , x) {
// Create a new Node
var head = head_ref;
var temp = new Node(x);
// if the list is empty, make the new Node head
// Also, it will point to itself.
if (head == null) {
temp.next = temp;
head_ref = temp;
return head_ref;
}
// traverse the list to reach the last Node
// and insert the Node
else {
var temp1 = head;
while (temp1.next != head)
temp1 = temp1.next;
temp1.next = temp;
temp.next = head;
}
return head;
}
/* Driver code */
// insert Nodes in the circular linked list
var head = null;
head = insertNode(head, 1);
head = insertNode(head, 2);
head = insertNode(head, 3);
head = insertNode(head, 4);
head = insertNode(head, 5);
head = insertNode(head, 6);
head = insertNode(head, 7);
head = insertNode(head, 8);
head = insertNode(head, 9);
var k = 4;
// Delete every kth Node from the
// circular linked list.
head = deleteK(head, k);
// This code is contributed by todaysgaurav
</script>
Output1->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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read