File tree 1 file changed +35
-0
lines changed 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Use a dummy head, and
3
+
4
+ l, r : define reversing range
5
+
6
+ pre, cur : used in reversing, standard reverse linked linked list method
7
+
8
+ jump : used to connect last node in previous k-group to first node in following k-group
9
+ """
10
+ class Solution :
11
+ def reverseKGroup (self , head : Optional [ListNode ], k : int ) -> Optional [ListNode ]:
12
+ # Dummy node initialization
13
+ dummy = jump = ListNode (- 1 )
14
+ dummy .next = l = r = head
15
+
16
+ while True :
17
+ count = 0
18
+ # Moving k positions
19
+ while r and count < k :
20
+ count += 1
21
+ r = r .next
22
+ # If count == k, then reverse the segment [l, r]
23
+ if count == k :
24
+ pre , cur = r , l
25
+ for _ in range (k ):
26
+ temp = cur .next
27
+ cur .next = pre
28
+ pre = cur
29
+ cur = temp
30
+ # Joining the current k-group with the previous k-group
31
+ jump .next = pre
32
+ jump = l
33
+ l = r
34
+ else :
35
+ return dummy .next
You can’t perform that action at this time.
0 commit comments