Created
October 5, 2019 07:17
-
-
Save sheldonrobinson/33aa33bb94e6963dbad1943a4ea93c91 to your computer and use it in GitHub Desktop.
CodeSignal solution reverseNodesInKGroups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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