# [leetcode] Reverse Nodes in k-Group

### Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: `1->2->3->4->5`

For k = 2, you should return: `2->1->4->3->5`

For k = 3, you should return: `3->2->1->4->5`

```/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
int count = 1;
ListNode * superHead = new ListNode(0);
ListNode * p = NULL;
while(count < k && p != NULL){
p = p->next;
count++;
}
count = 1;
if(p == NULL){//last group, don't reverse
continue;
}
else{//not the last group
p->next = NULL;
}
prevGroupTail->next = p;
while(prevGroupTail->next != NULL){
prevGroupTail = prevGroupTail->next;//move to prev group tail
}
}
return p;
}
ListNode * p1, * p2, * p3;
}
else{
p1 = NULL;
while(p2 != NULL){
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
return p1;
}
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.