# Simple Python solution, one pass, no additional space, 109ms

• The key idea is to keep track of the `next_head` while reversing the group, `tail` of the current group is always the start node of the group, once the group reversing is done, `next_head` is available, simply connect it to `tail`.

``````def reverseKGroup(self, head, k):
if head is None or k < 2:

for i in range(k - 1):

tail = current
prev = None
for i in range(k):
_next = current.next
current.next = prev
prev = current
current = _next

return ret``````

• Also the recursive solution:

``````def reverseKGroup(self, head, k):
if head is None or k < 2:

for i in range(k - 1):
ret = ret.next
if ret is None:

for i in range(k):
_next = current.next
current.next = prev
prev = current
current = _next

return ret    ``````

• Neat solution! Chuntao you are awesome!

• @ray8 thank you :)

• Really nice solution! Thanks for sharing, and this is my JAVA version:

``````public ListNode reverseKGroup(ListNode head, int k) {
if (k < 2) return head;
int cnt = 0;
while (next_head != null && cnt++ < k - 1) {
}
cnt = 0;
ListNode tail = curr;
ListNode pre = null;
while (cnt++ < k) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
}
return ret;
}``````

• Sorry, but this is certainly not 1-pass.

According to your code, You first move forward to make sure that you have k-nodes. If you don't you stop the search.
If you have k nodes, then you begin again and reverse the k-nodes.

The only way you could even be close to calling this as a single-pass solution is if you used a fast and slow pointer. And reverse in k-groups until the fast pointer hits None.

• @humachine agreed. not one pass at all... lol

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.