File tree 2 files changed +42
-1
lines changed
2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change 383
383
| 64| [ Minimum Path Sum] ( https://leetcode.com/problems/minimum-path-sum/ ) | | Medium|
384
384
| 63| [ Unique Paths II] ( https://leetcode.com/problems/unique-paths-ii/ ) | | Medium|
385
385
| 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|
387
387
| 60| [ Permutation Sequence] ( https://leetcode.com/problems/permutation-sequence/ ) | | Medium|
388
388
| 59| [ Spiral Matrix II] ( https://leetcode.com/problems/spiral-matrix-ii/ ) | | Medium|
389
389
| 58| [ Length of Last Word] ( https://leetcode.com/problems/length-of-last-word/ ) | | Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments