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

链表内指定区间反转

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

  public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if((m-n)==0) return head;
        //寻找断口
        int count=1;
        //移动指针
        ListNode pre=head;
        //移动指针前位
        ListNode front=null;
        //移动指针后位
        ListNode rear=null;
        //记录链表断口
        ListNode node10=null;
        ListNode node11;
        ListNode node20=null;
        ListNode node21;
        while(count<=n) 
        {
            if(count==(m-1)) node10=pre;
            if(count==n) node20=pre;   
            pre=pre.next;
            count++;
        }
        if(node10==null) node11=head;
        else node11=node10.next;
        node21=node20.next;
        
        //反转链表
        pre=node11.next;
        front=node11;
        rear=pre.next;
        int temp=n-m;
        if(temp==1)
            node20.next=node11;
        while(temp>=2)
        {
            pre.next=front;
            temp--;
            front=pre;
            pre=rear;
            rear=pre.next;
            if(temp==1) pre.next=front;
        }
        node11.next=node21;  
        if(m==1) head=node20;
        else node10.next=node20;
        return head;
    }

全部评论

相关推荐

07-24 16:39
已编辑
门头沟学院 测试开发
点赞 评论 收藏
分享
07-16 18:03
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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