题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 *
 * @param head ListNode类
 * @param m int整型
 * @param n int整型
 * @return ListNode类
 */
function reverseBetween(head, m, n) {
    // write code here
    const myReverse = (head, tail) => {
        let prev = tail.next;
        let p = head;
        while (prev !== tail) {
            const nex = p.next;
            p.next = prev;
            prev = p;
            p = nex;
        }
        return [tail, head];
    };
    const dummy = new ListNode(0);
    dummy.next = head;
    let pre = dummy;
    let mpHead = head;
    let npTail = head;
    for (let i = 1; i < m; i++) {
        pre = pre.next;
        mpHead = mpHead.next
    }
    for (let i = 1; i < n; i++) {
        npTail = npTail.next
    }
    const nex = npTail.next;
    [mpHead, npTail] = myReverse(mpHead, npTail);
    pre.next = mpHead;
    npTail.next = nex;
    return dummy.next;
}
module.exports = {
    reverseBetween: reverseBetween,
};

全部评论

相关推荐

11-26 22:34
已编辑
重庆邮电大学 Java
快手 客户端开发 (n+5)k*16 公积金12
牛客895077908号:佬 什么双非硕啊
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务