Skip to content

Instantly share code, notes, and snippets.

@sheldonrobinson
Created October 5, 2019 07:17
Show Gist options
  • Select an option

  • Save sheldonrobinson/33aa33bb94e6963dbad1943a4ea93c91 to your computer and use it in GitHub Desktop.

Select an option

Save sheldonrobinson/33aa33bb94e6963dbad1943a4ea93c91 to your computer and use it in GitHub Desktop.
CodeSignal solution reverseNodesInKGroups
def reverseList(head, tail):
prev = None
while prev != tail:
prev, prev.next, head = head, prev, head.next
return prev
def reverseNodesInKGroups(l, k):
if k < 2:
return l
p = ListNode(-1)
p.next = l
ret = p
while True:
flag = True
tmp = p
for i in range(k):
if tmp.next:
tmp = tmp.next
else:
flag = False
break
if flag:
q = tmp.next
t = p.next
reverseList(t, tmp)
p.next = tmp
t.next = q
p = t
else:
break
return ret.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment