-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.py
31 lines (30 loc) · 883 Bytes
/
Solution.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
def reverseList(head):
pre, p = None, head
while p:
q = p.next
p.next = pre
pre = p
p = q
return pre
dummy = ListNode(next=head)
pre = cur = dummy
while cur.next:
for _ in range(k):
cur = cur.next
if cur is None:
return dummy.next
t = cur.next
cur.next = None
start = pre.next
pre.next = reverseList(start)
start.next = t
pre = start
cur = pre
return dummy.next