题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
先找出翻转区间前一个节点left和后一个节点right,然后用常规的翻转链表方法把翻转区间翻转。最后拼接起来。注意翻转区间的最后要设null打断,防止无限循环
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
function reverse(head) {
let pre = null;
let cur = head;
let next;
while(cur) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return [pre, head];
}
function reverseBetween( head , m , n ) {
// 增加一个origin方便返回最终结果 origin.next
// 因为head也有可能被翻转了
const origin = { next: head };
head = origin;
let left, right;
let i = 0;
for(; i < m - 1; i++) {
head = head.next;
}
left = head;
for(; i < n; i++) {
head = head.next;
}
right = head.next;
head.next = null;
const [ start, end ] = reverse(left.next);
left.next = start;
end.next = right;
return origin.next
}
module.exports = {
reverseBetween : reverseBetween
};