栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

BM2 链表内指定区间反转java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

BM2 链表内指定区间反转java

描述
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
例如:
给出的链表为 1to 2 to 3 to 4 to 5 to NULL1→2→3→4→5→NULL, m=2,n=4m=2,n=4,
返回 1to 4to 3to 2to 5to NULL1→4→3→2→5→NULL.

数据范围: 链表长度 0 < size le 10000 要求:时间复杂度 O(n)O(n) ,空间复杂度 O(n)O(n)
进阶:时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)

import java.util.*;



public class Solution {
    
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
         //first和last分别确定m和n的位置,
        //prefirst用于确定节点m的前一个节点,end用于确定节点n的后一个节点
        //p,q,r用于区间m和n中的节点反转
        ListNode p,first,last,prefirst;
        ListNode q,r,end;
        p=head;
        first=head;
        prefirst=head;
        last=head;
        end=head;
        if(head==null) return null;
        if(m==n) return head;
        int number1=1;
        int number2=1;
        while(p!=null){
            if(number1==(m-1)){
                prefirst=p;
                first=p.next;
            }
            if(number2==n){
                last=p;
                end=p.next;
                break;
            }
            p=p.next;
            number1++;
            number2++;
        }
        p=first;
        q=p.next;
        p.next=end;
        r=q;
        while(r!=end){
            r=q.next;
            q.next=p;
            p=q;
            q=r;
        }
        if(m!=1){
            prefirst.next=last;
        }else{
            head=p;
        }
        
        return head;
}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782486.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号