
大致思路:1. 找到m位置 2. 在后续的遍历中对链表进行反向 3. 调整指针指向。
准备工作:设置一个哨兵i初始值为1,设置一个头结点first,值为1(防止第一个结点换到后面)。设置pre指针初始值为first,找到需要反转的区间前一个节点;last初始值为null,为cur当前节点的前一个节点;cur初始值为head,遍历链表节点;tmp为null,记录当前节点的下一个节点;将pre.next置为head。
public class Solution {
public ListNode reverseBetween (ListNode head, int m, int n) {
if(head.next==null || m==n) return head;
int i = 1;
ListNode first = new ListNode(1);
ListNode pre = first,last = null,cur = head,tmp = null;
pre.next = head;
while(i<m){
tmp = cur.next;
pre = cur;
cur = cur.next;
i++;
}
first.val = i;
while(i<n){
tmp = cur.next;
cur.next = last;
last = cur;
cur = tmp;
i++;
}
tmp = cur.next;
pre.next.next = tmp;
pre.next = cur;
cur.next = last;
if(pre.val==1) return first.next;
return head;
}
}