/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null||m>n||m<=0){
return null;
}
int len=0;
ListNode tmp=head;
while(tmp!=null){
tmp=tmp.next;
len++;
}
if(n>len){
return null;
}
if(m==n){
return head;
}
ListNode pCur=head;
ListNode pPre=null;
ListNode pNext=null;
int step=1;
while(pCur!=null&&step<m){
pPre=pCur;
pCur=pCur.next;
step++;
}
ListNode insert1 = pPre;
ListNode insert2 = pCur;
pPre=null;
while(pCur!=null&&step<=n){
pNext = pCur.next;
pCur.next=pPre;
pPre = pCur;
pCur = pNext;
step++;
}
if(insert1!=null){
insert1.next=pPre;
}else{
head=pPre;
}
insert2.next=pCur;
return head;
}
}
Reverse Linked List II
最新推荐文章于 2024-01-12 14:53:46 发布