-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathreverse_k_group.py
106 lines (89 loc) · 3.19 KB
/
reverse_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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
from typing import Optional
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
class Solution:
def reverse(self, head: Optional[ListNode], k: int) -> tuple[Optional[ListNode], Optional[ListNode], Optional[ListNode], bool]:
"""
Reverse the next k nodes in a linked list.
Args:
head (Optional[ListNode]): The head of the linked list.
k (int): The number of nodes to reverse.
Returns:
tuple[Optional[ListNode], Optional[ListNode], Optional[ListNode], bool]:
- The new head of the reversed group.
- The tail of the reversed group.
- The new head after the reversed group.
- A boolean indicating if there are more nodes to reverse.
Example:
>>> sol = Solution()
>>> head = ListNode(1)
>>> head.next = ListNode(2)
>>> head.next.next = ListNode(3)
>>> head.next.next.next = ListNode(4)
>>> head.next.next.next.next = ListNode(5)
>>> reversed_head, tail, new_head, found = sol.reverse(head, 2)
>>> reversed_head.val
2
>>> tail.val
1
>>> new_head.val
3
>>> found
True
"""
prev_group_end = None
remaining_count = k
current_group_start = head
# Calculate the remaining nodes in the list
while current_group_start:
current_group_start = current_group_start.next
remaining_count -= 1
# If there are less than k nodes remaining, return the original head
if remaining_count > 0:
return head, None, None, False
current_group_end = head
while head and k > 0:
k -= 1
next_node = head.next
head.next = prev_group_end
prev_group_end = head
head = next_node
return prev_group_end, current_group_end, head, True
def reverse_k_group(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""
Reverse nodes in a linked list in groups of k.
Args:
head (Optional[ListNode]): The head of the linked list.
k (int): The number of nodes in each group to reverse.
Returns:
Optional[ListNode]: The new head of the reversed linked list.
Example:
>>> sol = Solution()
>>> head = ListNode(1)
>>> head.next = ListNode(2)
>>> head.next.next = ListNode(3)
>>> head.next.next.next = ListNode(4)
>>> head.next.next.next.next = ListNode(5)
>>> new_head = sol.reverse_k_group(head, 2)
>>> new_head.val
2
>>> new_head.next.val
1
>>> new_head.next.next.val
4
>>> new_head.next.next.next.val
3
>>> new_head.next.next.next.next.val
5
"""
reversed_head, tail, new_head, found = self.reverse(head, k)
while found:
group_head, group_tail, new_head, found = self.reverse(new_head, k)
tail.next = group_head
tail = group_tail
return reversed_head
if __name__ == "__main__":
import doctest
doctest.testmod()