Skip to content

Commit 47a2dd8

Browse files
committedJan 3, 2023
23w1: add leetcode 61 solution
1 parent bb094ef commit 47a2dd8

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed
 

‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@
383383
|64|[Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)| |Medium|
384384
|63|[Unique Paths II](https://leetcode.com/problems/unique-paths-ii/)| |Medium|
385385
|62|[Unique Paths](https://leetcode.com/problems/unique-paths/)| |Medium|
386-
|61|[Rotate List](https://leetcode.com/problems/rotate-list/)| |Medium|
386+
|61|[Rotate List](https://leetcode.com/problems/rotate-list/)| [js](./algorithms/rotateList/Solution.js) |Medium|
387387
|60|[Permutation Sequence](https://leetcode.com/problems/permutation-sequence/)| |Medium|
388388
|59|[Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/)| |Medium|
389389
|58|[Length of Last Word](https://leetcode.com/problems/length-of-last-word/)| |Easy|

‎algorithms/rotateList/Solution.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @param {number} k
11+
* @return {ListNode}
12+
*/
13+
var rotateRight = function (head, k) {
14+
if (k === 0 || !head) {
15+
return head
16+
}
17+
let current = head
18+
let index = 0
19+
let length = 0
20+
while (current.next) {
21+
current = current.next
22+
length++
23+
}
24+
// 没计算尾节点因此需要再+1
25+
length++
26+
// k对长度取余,k有可能超过本身链表的长度
27+
let _k = k % length
28+
// 把首尾节点接上
29+
current.next = head
30+
current = head
31+
// 继续遍历链表,当前节点加上旋转长度如果已经超出了长度,就代表是尾节点了
32+
while (current.next && index + _k < length - 1) {
33+
current = current.next
34+
index++
35+
}
36+
37+
// 当前节点是尾节点,需要断开
38+
const result = current.next
39+
current.next = null
40+
return result
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.