Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit acbf861

Browse files
authored
Create Reverse_Nodes_in_K_group.py
1 parent ec908ad commit acbf861

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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

0 commit comments

Comments
 (0)