题解 | #链表内指定区间反转#
链表内指定区间反转
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;
}
// 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;
}