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

链表内指定区间反转

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

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 m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        
        if(head == null || head.next == null) return head;

        ListNode headPre = null, tailNext = null;

        ListNode pHead = head, rhead = null, pTail = head, rtail = null;

        int i = 1, j = 1;

        while(pHead != null){
            if(i == m){
                headPre = null;
                rhead = pHead;
                break;
            }else if(i + 1 == m){
                headPre = pHead;
                rhead = headPre.next;
                break;
            }else{
                pHead = pHead.next;
                i++;
            }
        }

        while(pTail != null){
            if(j == n){
                tailNext = pTail.next;
                rtail = pTail;
                break;
            }else if(j + 1 == n){
                rtail = pTail.next;
                tailNext = rtail.next;
                break;
            }else{
                pTail = pTail.next;
                j++;
            }
        }

        if(headPre != null){
            headPre.next = null;
        }
        rtail.next = null;

        ListNode newReverseListTail = rhead;
        ListNode newReverseListHead = reverseChainList(rhead);

        if(headPre != null){
           headPre.next = newReverseListHead;
        }else{
            head = newReverseListHead;
        }

        newReverseListTail.next = tailNext;

        return head;
    }

    public ListNode reverseChainList(ListNode head){

        if(head == null || head.next == null) return head;

        ListNode tail = head.next, pHead = head.next;

        //断开头节点,独立后面的链表
        head.next = null;

        //反转后面的链表
        pHead = reverseChainList(pHead);

        //把头节点跟新的尾链表连接上
        tail.next = head;
        tail = head;
        head = pHead;

        return head;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 14:32
点赞 评论 收藏
分享
机械打工仔:我来告诉你原因,是因为sobb有在线简历,有些HR为了快会直接先看在线简历,初步感觉不合适就不会找你要详细的了
投了多少份简历才上岸
点赞 评论 收藏
分享
真烦好烦真烦:豆包润色了自己没看看吗,再说了,都说豆包是愚蠢且勤快的大学生,ds才是聪明的研究生,怎么敢让豆包写论文的
你们的毕业论文什么进度了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:47
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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