注意边界问题
class Solution
{
public:
ListNode *reverseBetween(ListNode *head, int m, int n)
{
ListNode dummy(-1);
dummy.next = head;
ListNode *pre = &dummy;
for (int i = 0; i < m - 1; ++i)
pre = pre->next;
ListNode *const nHead = pre;
pre = nHead->next;
ListNode *cur = pre->next;
for (int i = m; i < n; ++i)
{
// 1->2->3->4->5
// 1->3->2->4->5
// 1->4->3->2->5
// 保存下一个要操作的
pre->next = cur->next;
// 头插法
cur->next = nHead->next;
nHead->next = cur;
// 取出下一个要操作的
cur = pre->next;
}
return dummy.next;
}
};