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

链表内指定区间反转

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-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务