-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_nodes_in_k_group.py
More file actions
40 lines (32 loc) · 996 Bytes
/
reverse_nodes_in_k_group.py
File metadata and controls
40 lines (32 loc) · 996 Bytes
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
from src.common import ListNode
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or k == 1:
return head
# Count the length of the linked list
length = 0
curr = head
while curr:
length += 1
curr = curr.next
# Create a dummy node
dummy = ListNode(0)
dummy.next = head
prev = dummy
# Process each group
curr = head
for i in range(0, length - length % k, k):
# Start of current group
start = curr
# Reverse k nodes
prev_node = None
for j in range(k):
next_node = curr.next
curr.next = prev_node
prev_node = curr
curr = next_node
# Connect with the rest of the list
prev.next = prev_node
start.next = curr
prev = start
return dummy.next