反转链表2

92. 反转链表 II

考虑到头部也可能产生反转,所以需要一个虚拟头。

在遍历的过程中记录反转后的尾节点和之前的节点。

最后进行节点的链接处理。

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
var reverseBetween = function(head, m, n) {
let noob = new ListNode(0)
noob.next = head
let cur = noob
let index = 0
let A,B
while (index < m) {
A = cur // A 记录反转子链的前一个节点
cur = cur.next
index++
}
B = cur // B 记录反转之后的尾节点
let pre = cur
while (index <= n) {
let next = cur.next
cur.next = pre
pre = cur
cur = next
index++
}
// 执行完后cur 指针在反转子链的下一个节点
B.next = cur
A.next = pre
return noob.next
};