Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
与反转链表的思路类似,但此时还应该记录第m-1个节点,如果它不为空,就要指向
反转链表的开头,还要记录第n+1个节点,反转链表指向它。是可以定义一个变量i,
判断是等于m-1,m,n在一个循环中得到所有需要记录的节点。
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n)
return head;
int i=0;
//记录第m-1个节点,m个节点,n+1个节点
ListNode l0=null,node=head;
ListNode l1=new ListNode(0),l2=new ListNode(0);
while(node!=null){
i++;
if(i==m-1)
l0=node;
if(i==m)
l1.next=node;
if(i==n){
l2.next=node.next;
node.next=null;
}
node=node.next;
}
if(l1.next==null)
return head;
//reverse (m,n)
ListNode p1=l1.next,p2=p1.next;
p1.next=l2.next;
while(p1!=null&&p2!=null){
ListNode t=p2.next;
p2.next=p1;
p1=p2;
p2=t;
}
//connect to previous part
if(l0!=null)
l0.next=p1;
else
return p1;
return head;
}