# Remove every Kth node of the Linked list

### Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Having a good grasp of Linked Lists can be a huge plus point in a coding interview.

### Problem Statement

Given a singly linked list and a value K, the task is to remove every Kth node of the linked list.

### Problem Statement Understanding

Let’s try to understand the problem statement with help of example.

We have been given a linked list, our task is to remove every Kth node from the linked list.

To understand the question thoroughly, see the given input below. In this input, the given value of K is 2. So, we have to delete every 2nd node of the linked list which are 23, 11, and 6.

#### Example:

Input: Output: Explanation: I think from the above example the problem statement is clear, so we should now think how we can approach this problem. Try to come up with a approach, it may be bruteforce but before jumping to approach section try to think how will you approach it.

### Approach

The idea is to traverse the list from the beginning and if the index of the current node is divisible by K, then delete the current node.

### Algorithm

• Take two pointer variables, current and previous.
• Initialize the current = head and previous = NULL.
• If the current node’s index is divisible by K, then delete this node and move current = current→next.
• If the current node’s index is not divisible by K, then move previous = current and current = current→next.

### Dry Run   ### Code Implementation

```#include
using namespace std;

struct Node {
int data;
struct Node* next;
};

{
Node *curr = head, *prv = NULL;
int index = 1;
/* Edge case
If K = 1 means every node has to be deleted
that is why we first delete every node and
then return the empty Linked list as NULL. */
if(K==1){
return NULL;
}
while(curr!=NULL){
/* If current node’s index is divisible
by K then, delete the current Node.*/
if(index%K==0){
Node* temp = curr;
curr = curr->next;
prv->next=curr;
temp->next=NULL;
delete temp;
}else{
prv = curr;
curr = curr->next;
}
index++;
}
}

void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
}

int main()
{

cout << temp->data << " ";
cout<next)
cout << temp->data << " ";

return 0;
}
```