有一说一,这题有点绕。。要找四个点才能解。
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
auto dummy = new ListNode(0, head);
//pre是反转开始节点的前一个节点,st为反转开始节点
//ed是反转最后一个节点,after是反转最后节点的后一节点
auto pre = dummy, ed = dummy;
for (int i = 0; i < m - 1; i ++ ) pre = pre->next;
for (int i = 0; i < n; i ++ ) ed = ed->next;
auto st = pre->next, after = ed->next;
auto p1 = st, p2 = st->next; //这一段是反转链表模板
while (p2 != after)
{
auto p3 = p2->next;
p2->next = p1;
p1 = p2, p2 = p3;
}
pre->next = ed;
st->next = after;
return dummy->next;
}
};