-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |