Open larscheng opened 3 months ago
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1,head);
ListNode pre = dummy;
for (int i = 1; i < left; i++) {
//反转区前一个节点
pre = pre.next;
}
//依次遍历反转区元素,将反转区元素往前移
//...[pre][cur][next]...--->....[pre][next][cur]....
//cur.next=next.next,pre.next=next,next.next=cur
ListNode cur = pre.next;
ListNode next = null;
for (int i = 0; i < right-left; i++) {
//每次移位后cur和next的位置都会变化,pre不变
next = cur.next;
//移位
cur.next = next.next;
next.next = pre.next;//这里要用pre.next不能用cur,因为在移位的过程中cur会改变位置
pre.next = next;
}
return dummy.next;
}
}
92. 反转链表 II