链表内指定区间反转

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null)
return null;
ListNode preHead=new ListNode(0);
preHead.next=head;
ListNode  head0=head;
ListNode head1= head;
ListNode tempList=null;
ListNode node1=null,node2=null,next=null,pre=null;
//当节点为第一个节点时
if(m==1)
pre=preHead;
//循环找到指定的节点的前一个节点
for(int i=0; i<m-1; i++){
if(i==0)
pre=preHead;
pre=pre.next;

}
//找到要反转节点的位置
node1=pre.next;
ListNode temp=node1;
//循环找到要反转的链表的最后一个节点

for(int i=0; i<n-m; i++){
node2=temp.next;
temp= temp.next;
}
// 分类讨论,当节点m=n时候
if(m==n){
node2=temp;
next=node2.next;
node2.next=null;
}
// m!=n时
else{
next=node2.next;
node2.next=null;
}
// 调用第一题反转链表的函数
tempList=run(node1);
// 将前驱节点指向反转链表首部
pre.next=tempList;
// 找到反转链表的最后一个元素
while(tempList.next!=null){
tempList=tempList.next;
}
// 将将反转链表的最后一个元素指向原链表位置的下一个元素
tempList.next=next;

//返回头节点
return  preHead.next;
}
//反转链表函数
public static ListNode run(ListNode head){
  if(head==null)

            return null;

            ListNode reversedHead=null;
            ListNode current=head;
            ListNode tmp=null;
        

            while(current!=null){
            tmp= current;
            current= current.next;
            tmp.next=null;
            if(reversedHead==null)
            reversedHead=tmp;
            else{
                tmp.next=reversedHead;
                reversedHead=tmp;
            }
            
     }
            return reversedHead;
     }

}
全部评论

相关推荐

07-18 14:55
门头沟学院 Java
点赞 评论 收藏
分享
彧未sr:查看图片
投递牧原集团等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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