-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path61.rotate-list.js
More file actions
59 lines (56 loc) · 1.07 KB
/
61.rotate-list.js
File metadata and controls
59 lines (56 loc) · 1.07 KB
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
/*
* @lc app=leetcode id=61 lang=javascript
*
* [61] Rotate List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
function listLength(head) {
let count = 0;
while (head) {
count++;
head = head.next;
}
return count;
}
var rotateRight = function (head, k) {
let len = listLength(head);
if (len === 0) {
return head;
} else {
k = k % len;
if (k === 0) {
return head;
}
}
let headPointer = head,
tailPointer = head,
headStart = k;
while (headPointer.next) {
if (headStart === 0) {
tailPointer = tailPointer.next;
} else {
headStart--;
}
headPointer = headPointer.next;
}
headPointer.next = head;
head = tailPointer.next;
tailPointer.next = null;
return head;
};
// @lc code=end
// @after-stub-for-debug-begin
module.exports = rotateRight;
// @after-stub-for-debug-end