题目描述
思路
对于反转m到n的问题,
- 确定好循环次数,pre是不动的,循环内:
- 先cur.next = ...
- 再tmp.next = ...
- 再pre.next = ...
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;//
for (int i = m; i > 1; i--) {//找到开始节点的前一个节点
pre = pre.next;
}
ListNode cur = pre.next;//开始节点
for (int i = 0; i < n - m; i++) {//逐个往前提
ListNode tmp = cur.next;
cur.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
}
return dummy.next;
}
}