forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25.reverse-nodes-in-k-group.py
53 lines (40 loc) · 1.21 KB
/
25.reverse-nodes-in-k-group.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head is None:
return None
new_head = ListNode(0)
new_head.next = head
start = new_head
while start.next is not None:
end = start
for _ in range(k):
end = end.next
if end == None:
return new_head.next
results = self.reverse(start, end)
start.next = results[0]
start = results[1]
return new_head.next
# start -> n1 -> n2 ... nk
# start -> nk -> nk-1 ... n1
# return nk -> nk-1 .... n1
def reverse(self, start, end):
current = start.next
while start.next != end:
pre = current
current = current.next
pre.next = current.next
current.next = start.next
start.next = current
current = pre
return [start.next, current]