给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

思路

  1. 添加 dummyHead
  2. 找到 left 节点的前驱节点 keyPrev
  3. keyTail = leftNode,keyTail 为翻转后的链表段尾节点
  4. 翻转过程中始终保证链表的连续性,keyTail.next = remainLink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var reverseBetween = function (head, left, right) {
const dummyHead = new ListNode()
dummyHead.next = head
let keyPrev = dummyHead
for (let i = 1; i < left; ++i) {
keyPrev = keyPrev.next
}
let cur = keyPrev.next
let keyTail = cur
let newLink = null
let steps = right - left + 1
while (cur && steps--) {
const remainLink = cur.next
cur.next = newLink
newLink = cur
keyTail.next = remainLink
cur = remainLink
}
keyPrev.next = newLink
return dummyHead.next
}