-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path92.反转链表-ii.js
44 lines (40 loc) · 904 Bytes
/
92.反转链表-ii.js
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
/*
* @lc app=leetcode.cn id=92 lang=javascript
*
* [92] 反转链表 II
*/
// @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} left
* @param {number} right
* @return {ListNode}
*/
// [1, 2, 3, | [4, 5, 6], 7, 8, 9]
var reverseBetween = function(head, left, right) {
if (left == 1) {
return reverseN(head, right) // reverse first N value!
}
head.next = reverseBetween(head.next, left - 1, right - 1)
return head
}
let successor = null
function reverseN(head, n) {
if (n == 1) {
successor = head.next
return head
}
const last = reverseN(head.next, n - 1)
head.next.next = head
head.next = successor
return last
}
// @lc code=end
module.exports = { reverseBetween }