-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_25.py
38 lines (33 loc) · 989 Bytes
/
prob_25.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
# 25. Reverse Nodes in k-Group
# https://leetcode.com/problems/reverse-nodes-in-k-group/
# 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
"""
dummy = jump = ListNode(-1)
dummy.next = l = r = head
while True:
counter = 0
while counter<k and r is not None:
r = r.next
counter += 1
if counter == k:
pre, cur = r, l
for _ in range(k):
temp = cur.next
cur.next = pre
pre = cur
cur = temp
jump.next = pre
jump = l
l = r
else:
return dummy.next