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

牛群的重新排列

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;
    }
}

全部评论

相关推荐

头像 会员标识
01-14 15:08
东南大学 Java
点赞 评论 收藏
分享
Dream_coding:你是不是只投大厂了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务