File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
leetcode.com 61. Rotate List Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Optional
2
+
3
+
4
+ # Definition for singly-linked list.
5
+ class ListNode :
6
+ def __init__ (self , val = 0 , next = None ):
7
+ self .val = val
8
+ self .next = next
9
+
10
+
11
+ class Solution :
12
+ def rotateRight (self , head : Optional [ListNode ], k : int ) -> Optional [ListNode ]:
13
+ # linked list length is 1
14
+ if head is None or head .next is None :
15
+ return head
16
+
17
+ length = 0
18
+ node = head
19
+ while node :
20
+ length += 1
21
+ node = node .next
22
+
23
+ k = k % length
24
+
25
+ # from here, linked list length is 2 at least
26
+ for _ in range (k ):
27
+ tail = self .get_tail (head )
28
+ tail .next = head
29
+ head = tail
30
+
31
+ return head
32
+
33
+ def get_tail (self , node : Optional [ListNode ]):
34
+ prev = node
35
+ node = node .next
36
+
37
+ while node .next :
38
+ prev = node
39
+ node = node .next
40
+
41
+ prev .next = None
42
+ return node
You can’t perform that action at this time.
0 commit comments