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

链表内指定区间反转

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
    if (!head || !head.next || m === n) {
        return head;
    }
    let headKeep;
    let tailKeep;
    let between;
    let cur = head;
    let i = 1;
    while (cur && i <= n + 1) {
        let temp = cur;
        cur = cur.next;
        if (i < m) {
            if (!headKeep) {
                headKeep = temp;
                headKeep.next = null;
            } else {
                headKeep.next = temp;
                headKeep = headKeep.next;
            }
        }
        if (i >= m && i <= n) {
            if (!between) {
                between = temp;
                between.next = null;
            } else {
                temp.next = between;
                between = temp;
            }
        }
        if (i > n) {
            tailKeep = temp;
        }
        i++;
    }
    if (headKeep) {
        headKeep.next = between;
    } else {
        head = between;
    }
    if (tailKeep) {
        let btw = between;
        while (btw) {
            if (!btw.next) {
                btw.next = tailKeep;
                return head;
            }
            btw = btw.next;
        }
    }
    return head;
}
module.exports = {
    reverseBetween: reverseBetween,
};

结题思路:把链表拆分成3部分,头部不变序段,中间m-n反转段以及末尾段,中间反转,然后首中尾相连,重新组合

#链表调整顺序#
全部评论

相关推荐

11-24 11:23
门头沟学院 C++
点赞 评论 收藏
分享
菜菜咪:1. 可以使用简历网站的模版,美观度会更好一点 2. 邮箱可以重新申请一个,或者用qq邮箱的别名,部分hr可能会不喜欢数字邮箱 3. 项目经历最好分点描述,类似的项目很多,可以参考一下别人怎么写的 4. 自我评价可加可不加,技术岗更看重技术。最后,加油,优秀士兵
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务