-
Notifications
You must be signed in to change notification settings - Fork 0
/
92.js
54 lines (49 loc) · 1.41 KB
/
92.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
45
46
47
48
49
50
51
52
53
54
/**
* 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}
*/
let reverseBetween = function(head, left, right) {
if (left === 1) {
return reverseHead(head, right)
}
head.next = reverseBetween(head.next, left - 1, right - 1)
return head
};
let nextNode = null
let reverseHead = function(head, n) {
if (n === 1) {
nextNode = head.next
return head
}
let newHead = reverseHead(head.next, n - 1)
head.next.next = head
head.next = nextNode
return newHead
}
/*
2021/7/31
反转链表加强版
先将反转整个链表优化为反转整个链表的前N项
通过迭代链表并递减N,在basecase处记录反转前最后一个节点(新头节点)的下一个节点,再对前N项执行反转整个链表,将原头节点的next节点设置为之前记录的节点(而不是null)
再通过迭代递减left直至left为1,将反转left和right之间的节点转换为反转前N个节点(因为此时left为1)
*/
// 递归解法
let reverseHead = (head, right) => {
let prev, cur = head
while (cur !== right) {
const nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
}
return prev
}