# 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,

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

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

Tips:

Code：

``````public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {

ListNode dummy = new ListNode(0);

ListNode tail = dummy;
ListNode prev = dummy;

int count;
while(true){
count =k;
while(count>0&&tail!=null){
count--;
tail=tail.next;
}
if (tail==null) break;//Has reached the end
// prev-->temp-->...--->....--->tail-->....
// Delete @temp and insert to the next position of @tail
// Assign @temp to the next node of @prev
// prev-->temp-->...-->tail-->...-->...
// Keep doing until @tail is the next node of @prev
while(prev.next!=tail){
ListNode temp=prev.next;//Assign
prev.next=temp.next;//Delete

temp.next=tail.next;
tail.next=temp;//Insert

}

}
return dummy.next;

}
}
``````

LintCode:

``````public ListNode reverseBetween(ListNode head, int m , int n) {
}
ListNode dummyNode = new ListNode(0);
ListNode preReverse = dummyNode;
for (int i = 0; i < m-1; i++){
if (preReverse.next == null) {
return null;
}
preReverse = preReverse.next;
}
ListNode first = preReverse.next;
ListNode postReverse = preReverse.next;
for (int i = 0; i < n-m; i++){
if (postReverse == null){
return null;
}
postReverse = postReverse.next;
}
preReverse.next = postReverse;
ListNode last = postReverse;
postReverse = postReverse.next;
for (int i = 0; i < n-m+1; i++){
ListNode temp = first.next;
first.next = postReverse;
postReverse = first;
first = temp;
}
return dummyNode.next;
}
``````