Skip to content

Commit 5624641

Browse files
committed
Add solution #61
1 parent b3607e5 commit 5624641

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
6767
59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium|
6868
60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard|
69+
61|[Rotate List](./0061-rotate-list.js)|Medium|
6970
62|[Unique Paths](./0062-unique-paths.js)|Medium|
7071
64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium|
7172
65|[Valid Number](./0065-valid-number.js)|Hard|

solutions/0061-rotate-list.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 61. Rotate List
3+
* https://leetcode.com/problems/rotate-list/
4+
* Difficulty: Medium
5+
*
6+
* Given the head of a linked list, rotate the list to the right by k places.
7+
*/
8+
9+
/**
10+
* Definition for singly-linked list.
11+
* function ListNode(val, next) {
12+
* this.val = (val===undefined ? 0 : val)
13+
* this.next = (next===undefined ? null : next)
14+
* }
15+
*/
16+
/**
17+
* @param {ListNode} head
18+
* @param {number} k
19+
* @return {ListNode}
20+
*/
21+
var rotateRight = function(head, k) {
22+
if (!head || !head.next || !k) return head;
23+
let tailCopy = head;
24+
let tail = head;
25+
let count = 1;
26+
while (tail.next) {
27+
tail = tail.next;
28+
count++;
29+
}
30+
tail.next = head;
31+
for (let i = 1; i < count - k % count; i++) {
32+
tailCopy = tailCopy.next;
33+
}
34+
const result = tailCopy.next;
35+
tailCopy.next = null;
36+
return result;
37+
};

0 commit comments

Comments
 (0)