BiruLyu
7/31/2017 - 5:25 PM

## 25. Reverse Nodes in k-Group(#iterative).java

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || k ==1){
}

ListNode dummy = new ListNode(0);

ListNode prev = dummy;
int count = 0;
while(next!=null){
next = next.next;
count++;
if(count == k){
prev= reverse(prev, next);
count = 0;
}
}
return dummy.next;

}

private static ListNode reverse(ListNode prev, ListNode next){
ListNode last = prev.next;
ListNode cur = last.next;
while(cur!=next){
last.next = cur.next;
cur.next = prev.next;
prev.next = cur;
cur = last.next;
}
return last;
}
}``````
``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
// curr - head-pointer to reversed part;
while (count-- > 0) { // reverse current k-group:
ListNode tmp = head.next; // tmp - next head in direct part
curr = head; // move head of reversed part to a new node
head = tmp; // move "direct" head to the next node in direct part
}
}
}
}``````
``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {

public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(-1), pre = dummy,b egin = head;
int i = 0; // count the ordinal number of the node
i++;
if (i % k == 0) {
ListNode nextBegin = head.next; // store the next begin point
reverse(begin, head);  // reverse the begin node to the cur node
pre.next = head; // restore the given k nodes to the original link
pre = begin; // jump k nodes
begin = nextBegin;
} else {
}
}
return dummy.next;
}

private void reverse(ListNode start, ListNode end) {
while (start != end) {
ListNode next = start.next;
start.next = end.next;
end.next = start;
//end = start;
start = next;
}

}

}``````