Skip to content

Commit 94cd74b

Browse files
authored
Update 61-rotate-list.js
1 parent 876eb6e commit 94cd74b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

61-rotate-list.js

+34
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,37 @@ const rotateRight = function(head, k) {
2929

3030
return dummy.next;
3131
};
32+
33+
// another
34+
35+
/**
36+
* Definition for singly-linked list.
37+
* function ListNode(val, next) {
38+
* this.val = (val===undefined ? 0 : val)
39+
* this.next = (next===undefined ? null : next)
40+
* }
41+
*/
42+
/**
43+
* @param {ListNode} head
44+
* @param {number} k
45+
* @return {ListNode}
46+
*/
47+
const rotateRight = function(head, k) {
48+
if(head == null) return null
49+
let len = 1
50+
let tmp = head
51+
while(tmp.next) {
52+
len++
53+
tmp = tmp.next
54+
}
55+
k = k % len
56+
if(k === 0) return head
57+
let tail = head
58+
for(let i = 1; i < len - k; i++) {
59+
tail = tail.next
60+
}
61+
const newHead = tail.next
62+
tmp.next = head
63+
tail.next = null
64+
return newHead
65+
};

0 commit comments

Comments
 (0)