思路1:迭代法(三指针)
定义一个头结点指向当前链表的表头,便于返回表头。指针pre指向节点m-1,指针after指向m,指针cur指向m+1,从m+1到n的所有节点都使用头插法插入pre之后
打个比方:m节点(小红) m+1节点(小明) n节点(小杨),请小明到小杨之间的同学(包括小明和小杨)依次插入小红的前面,首先你得知道小红在哪里,定位到小红前面一位同学,cur指针指向当前要插入的同学
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode pre=dummy;
ListNode after=dummy.next;
ListNode cur=null;
//找到m的前一节点
for(int i=1;i<left;i++)
{
pre=pre.next;
after=after.next;
}
//几个节点要插入
for(int i=0;i<right-left;i++)
{
cur=after.next;
//原链表节点摘下
after.next=after.next.next;
//头插法
cur.next=pre.next;
pre.next=cur;
}
return dummy.next;
}
}
时间O(N) 空间O(1)