Skip to content

Commit

Permalink
solve "61. Rotate List"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Nov 2, 2024
1 parent cd1701b commit b6628cc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/rotate_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from src.utils.linked_list import ListNode


def get_length(head: ListNode | None) -> int:
result = 0

while head:
result += 1
head = head.next

return result


class Solution:
def rotateRight(self, head: ListNode | None, k: int) -> ListNode | None:
n = get_length(head)

if n == 0 or n == 1:
return head

k = k % n
if k == 0:
return head

dummy = left = ListNode(next=head)

for _ in range(n - k):
assert left.next
left = left.next

new_start = left.next

last = left
while last and last.next:
last = last.next

dummy.next = new_start
last.next = head
left.next = None
return dummy.next
24 changes: 24 additions & 0 deletions tests/test_rotate_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import pytest

from src.rotate_list import Solution
from src.utils.linked_list import to_linked_list
from src.utils.linked_list import to_list


@pytest.mark.parametrize(
"in_list,k,expected_out_list",
(
([1, 2, 3, 4, 5], 2, [4, 5, 1, 2, 3]),
([0, 1, 2], 4, [2, 0, 1]),
([], 0, []),
([], 1, []),
([1], 1, [1]),
([1, 2], 2, [1, 2]),
([1], 99, [1]),
),
)
def test_solution(in_list, k, expected_out_list):
head = to_linked_list(in_list)
out_head = Solution().rotateRight(head, k)
out_list = to_list(out_head)
assert out_list == expected_out_list

0 comments on commit b6628cc

Please sign in to comment.