# Non-recursive Java solution and idea

• First, build a function reverse() to reverse the ListNode between begin and end. See the explanation below:

``````   /**
* Reverse a link list between begin and end exclusively
* an example:
* 0->1->2->3->4->5->6
* |           |
* begin       end
* after call begin = reverse(begin, end)
*
* 0->3->2->1->4->5->6
*          |  |
*      begin end
* @return the reversed list's 'begin' node, which is the precedence of node end
*/
``````

Then walk thru the linked list and apply reverse() iteratively. See the code below.

``````public ListNode reverseKGroup(ListNode head, int k) {
ListNode begin;
int i=0;
i++;
if (i%k == 0){
} else {
}
}

}

public ListNode reverse(ListNode begin, ListNode end){
ListNode curr = begin.next;
ListNode next, first;
ListNode prev = begin;
first = curr;
while (curr!=end){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
begin.next = prev;
first.next = curr;
return first;
}``````

• it's not the constant space

• why it's not the constant space?

• This post is deleted!

• It is constant space. No matter what the k is, you use the same number of ListNode references.

• beautiful solution

• Amazing Solution!! Specially the use of reverse. You have my upvote!

• Similar Idea:

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// Save the previous reversed pointer in prev and in wach iteration use prev.next to set the previous ptr to the current reversed.
ListNode tempNode = new ListNode(0);
ListNode prev = tempNode;
// Starting of each reversed list, it will become the last after reversing
int num = k;
// Jump k
num--;
}
// If cannot reverse
if(num!=0) {
prev.next = klast;
break;
}
// start of each reversed group
ListNode kstart = reverse(klast,k);

// Use previous's next to point to curr reversed
prev.next = kstart;
// Set prev to current rev end.
prev = klast;
}
return tempNode.next;

}

// Standard reverse code
public ListNode reverse(ListNode head, int k){
ListNode prev = null;