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

解法一:

public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if (head == null || m == n) return head; // 如果链表为空或反转区间只有一个节点

        ListNode pre = null, cur = head;

        // 1. 找到第 m-1 个节点 (pre) 和第 m 个节点 (cur)
        for (int i = 1; i < m; i++) {
            pre = cur;
            cur = cur.next;
        }

        // 2. 保存第 m 个节点前后的节点
        ListNode lastEnd = pre; // 记录第 m-1 个节点,反转后连接这里
        ListNode firstNode = cur; // 第 m 个节点,将成为反转后的最后一个节点

        // 3. 反转区间 [m, n] 内的节点
        ListNode next = null;
        for (int i = m; i <= n; i++) {
            next = cur.next;  
            cur.next = pre;  
            pre = cur;     
            cur = next;      
        }

        // 4. 两种情况,一种是m不为1,代表前面还有节点;另外一种代表m为1,就是第一个节点
        if (lastEnd != null) {
            lastEnd.next = pre; // 连接第 m-1 个节点与反转后的部分
        } else {
            head = pre; // 如果 m == 1,那么反转后的头节点为 pre
        }

        // 5. 将反转区间最后一个节点(即为反转区间的第m个节点)的 next 指向第 n+1 个节点
        firstNode.next = cur;

        return head;
}

解法二(思路来源于左神所讲的划分链表):

public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if (head == null || head.next == null || m == n) return head;

        ListNode p = head;
        ListNode lastEnd = null, curStart = null, curEnd = null, afterStart = null;
        int l = m, r = n;
        while (r > 0) {
            l--;
            r--;
            if (l > 0) {
                lastEnd = p;
            }
            if (l == 0) {
                curStart = p;
            }
            if (r == 0) {
                curEnd = p;
            }
            p = p.next;
        }

        ListNode cur = curStart;
        afterStart = curEnd.next;
        curEnd.next = null;

        ListNode pre = null, next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        if (lastEnd != null) {
            lastEnd.next = pre;
        }
        if (afterStart != null) {
            curStart.next = afterStart;
        }

        head = lastEnd == null? pre : head;
        return head;
    }

全部评论

相关推荐

来个大佬救一下,为上投了都是石沉大海了,没实习经历的话怕秋招直接进不了面。什么实习这么难找,基本
心态爆炸了:现在正式的岗位都少,实习基本不咋招的,除了大厂,中小企业其实没那么多岗位需求,就算是有,大多都是招一两个廉价劳动力,同时,他们也会希望你一来就能干活的,没时间培训你,就让你了解公司的项目,你了解完就可以开始干活。再者是,很多低质量的实习其实用处没有那么大的。我去年也是找实习找到破防,最后去了一家深圳的小公司实习,工作对我来说很简单,甚至不如我在学校做的项目,秋招的时候,这段实习经历也并没有帮上什么忙,投递简历,依旧非常低的回复率。低回复率是常态,尤其是找实习,找不到,那就把重心放在优化自己的简历和项目,多看八股文,锻炼自己的面试能力,多看别人的面经,自己模拟面试,等秋招的时候,只要有那么寥寥几次,好好抓住那几次机会。
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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