# Reverse every k nodes of a linked list

Given a linked list and a number k. Reverse every k nodes in the list.

Example :

Input 1->2->3->4->5->6 and k = 2
Output 2->1->4->3->6->5

Solution : We have a pointer q which points to the head of the list initially. Advance this k times in a while loop and keep reversing the list. Now q points to (k+1)th node and we call the same procedure on it. This function returns the head of the reversed list.

```struct node *reverseKNodes (struct node *head, int k)
{
struct node* r = NULL;
struct node* s;
int count = 0;

while (q != NULL && count < k)
{
s = r;
r = q;
q  = q->next;
r->next = s;
count++;
}

if(q !=  NULL)

return r;
}
```

### 3 Thoughts on “Reverse every k nodes of a linked list”

1. Thanks.

struct node* reverseKNodes(node* head, int k) {
node* prev = NULL;
node* next;
int count = 0;

while(cur != NULL && count next;
cur->next = prev;
prev = cur;
cur = next;
count++;
}

if(cur!=NULL) {
}

return prev;
}

2. RaghuNathan on March 3, 2015 at 11:54 pm said:

temp = NULL;
int value,nextValue ,count=0;

number can be any value.

nextValue = temp -> value;

if(count value = nextValue;
temp -> value = value;
}

count ++;