-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
69 lines (54 loc) · 1.14 KB
/
solution.ts
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
65
66
67
68
69
/*
* @lc app=leetcode id=61 lang=javascript
*
* [61] Rotate List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
type MaybeList = ListNode | null;
interface ListNode {
val: number;
next: MaybeList;
}
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
const rotateRight = (head: MaybeList, k: number): MaybeList => {
// * ['56 ms', '97.98 %', '35.7 MB', '100 %']
if (head === null || head.next === null) return head;
let ahead: ListNode = head;
let behind: ListNode = head;
let len = 0;
while (k > 0) {
k--;
len++;
if (ahead.next !== null) {
ahead = ahead.next;
} else {
ahead = head;
// * skip some loop, remain less k walking, and len is useless now
k = k % len;
}
}
if (ahead === behind) return head;
while (ahead.next) {
ahead = ahead.next;
behind = behind.next!;
}
const newEnd = behind;
const newHead = behind.next;
const end = ahead;
end.next = head;
newEnd.next = null;
return newHead;
};
// @lc code=end
export { rotateRight };