Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Oct 1, 2023
commit 3b45f3cf4e9ccd3a3b03e984f5c55a7653d75be7
21 changes: 18 additions & 3 deletions data_structures/linked_list/reverse_k_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

from dataclasses import dataclass


@dataclass
class ListNode:
data: int
next_node: ListNode | None = None


def print_linked_list(head: ListNode | None) -> None:
"""
Print the entire linked list iteratively.
Expand Down Expand Up @@ -34,6 +36,7 @@ def print_linked_list(head: ListNode | None) -> None:
head = head.next_node
print(head.data)


def insert_node(head: ListNode | None, data: int) -> ListNode:
"""
Insert a new node at the end of a linked list and return the new head.
Expand Down Expand Up @@ -62,8 +65,11 @@ def insert_node(head: ListNode | None, data: int) -> ListNode:
temp_node.next_node = new_node
return head


class Solution:
def reverse_k_group(self, head: ListNode | None, group_size: int) -> ListNode | None:
def reverse_k_group(
self, head: ListNode | None, group_size: int
) -> ListNode | None:
"""
Reverse k-sized groups of nodes in a linked list.

Expand All @@ -85,6 +91,7 @@ def reverse_k_group(self, head: ListNode | None, group_size: int) -> ListNode |
>>> print_linked_list(new_head)
2->1->4->3->6->5
"""

def reverse_group(head: ListNode | None, node_size: int) -> tuple:
prev_group_tail = None
nodes_left = node_size
Expand All @@ -108,16 +115,24 @@ def reverse_group(head: ListNode | None, node_size: int) -> tuple:

return prev_group_tail, current_tail, head, True

new_head, current_tail, next_group_head, success = reverse_group(head, group_size)
new_head, current_tail, next_group_head, success = reverse_group(
head, group_size
)

while success:
new_group_head, new_group_tail, next_next_group_head, success = reverse_group(next_group_head, group_size)
(
new_group_head,
new_group_tail,
next_next_group_head,
success,
) = reverse_group(next_group_head, group_size)
current_tail.next_node = new_group_head
current_tail = new_group_tail
next_group_head = next_next_group_head

return new_head


if __name__ == "__main__":
import doctest

Expand Down