def reverseKGroup(self, head, k):
helper=ListNode(0)
helper.next=head
q=helper
p=head
stack=[]
while p!=None :
if len(stack)==k:
while len(stack)>0:
q.next=stack.pop()
q=q.next
q.next=p
else:
stack.append(p)
p=p.next
if len(stack)==k:
while len(stack)>0:
q.next=stack.pop()
q=q.next
q.next=p
elif len(stack)>0:
q.next=stack[0]
return helper.next
Fast python code use stack , I think there is cleaner way to do.


The problem is that this solution uses O(k) space, not O(1). Besides, there are duplicate code. You are modify it like this to remove duplicates:
class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ dummy = ListNode(0) dummy.next, stack, node = head, [], dummy while head: stack.append(head) head = head.next if len(stack) == k: # pop out and reverse while stack: node.next = stack.pop() node = node.next node.next = head if stack: # connect the remaining ones node.next = stack[0] return dummy.next