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

链表内指定区间反转

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

/*class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head ListNode类
 * @param m int整型
 * @param n int整型
 * @return ListNode类
 */
export function reverseBetween(head: ListNode, m: number, n: number): ListNode {
    if (!head || m == n) return head;
    const dummy = new ListNode(0);
    dummy.next = head;
    let pre: ListNode = dummy;
    // 移动到前驱节点,即m-1个
    for (let i = 0; i < m-1; i++) {
        pre = pre.next;
    }
    let mNode = pre.next;
    let curr: ListNode | null = mNode;
    let prev: ListNode | null = null;
    let next: ListNode | null = null;

    // 反转n-m+1个节点
    for (let i = 0; i < (n - m + 1); i++) {
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    // 连接反转后的部分
    pre.next=prev
    mNode.next=curr

    return dummy.next
}

全部评论

相关推荐

买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务