-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61.py
64 lines (46 loc) · 1.59 KB
/
61.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
'''61. Rotate List
Created on 2025-01-07 22:12:57
2025-01-07 22:39:56
@author: MilkTea_shih
'''
#%% Packages
from typing import Optional, Self
#%% Variable
class ListNode:
def __init__(self, val=0, next=None) -> None:
self.val: int = val
self.next: Optional[Self] = next
#%% Functions
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int
) -> Optional[ListNode]:
if head is None or k == 0: #edge case and also `k` is 0, no rotate
return head
length: int = 1
current: ListNode = head
# Reach the node before the end of `head`.
while current is not None and current.next is not None:
length += 1
current = current.next
k %= length # `k // length` is the times to rotate whole `head`.
if k == 0: # `k` equals zero, which indicates there is no rotated.
return head
# Let the end of node point to the beginning of `head`.
current.next = head
current = head
# Reach the previous node at the rotated linked list.
for _ in range(length - k - 1):
current = current.next # type: ignore
head = current.next # The beginning of the rotated linked list.
current.next = None # The end node of the rotated linked list.
return head
#%% Main Function
#%% Main
if __name__ == '__main__':
pass
#%%