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

牛群的重新排列

https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param left int整型 
     * @param right int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int left, int right) {
        // write code here
        // 1. 特殊情况的处理
        if (head == null || head.next == null || left == right) return head;

        // 2. 为了避免边界问题的难处理性,此处引入一个新的头,让“边界”不再是“边界”
        ListNode newHead = new ListNode(-1);
        newHead.next = head;

        // 3. 先找到要反转的前驱节点
        ListNode pre = newHead;
        // ListNode cur = newHead;
        int L = left;
        while (L-- != 1) {
            pre = pre.next;
        }

        // 4. 开始反转
        ListNode start = pre.next;
        ListNode end = start;       // 记录开始反转的点,后续需要与剩余部分拼接
        ListNode cur = start.next;
        int count = right - left;
        while(count-- != 0) {
            ListNode next = cur.next;
            cur.next = start;
            start = cur;
            cur = next;
        }

        // 5. 走到此处链表如图:newHead  pre  start  end  cur   链表结尾  
        //                创建的新头节点 原来的right  left
        pre.next = start;
        end.next = cur;

        // 6. 返回节点即可
        return newHead.next;
    }
}

全部评论

相关推荐

测试糕手手:社会第一课,随便吹牛逼,直接说四个月,别老实。老实人只会被欺负
点赞 评论 收藏
分享
05-29 22:11
门头沟学院 Java
Elastic90:抛开学历造假不谈,这公司的招聘需求也挺怪的,Java开发还要求你有图文识别、移动端开发和c++的经验,有点逆天了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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