分为三步
- 用四个指针,分别指向反转位置p,q以及第一个反转元素的pre和最后一个元素的next
- 反转p,q之间的元素
- 根据pre和next的情况来重新连接
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m >= n || head == NULL)
return head;
ListNode* p, *q, *p_pre, *q_next, *itr;
p = q = p_pre = q_next = itr = NULL;
itr = head;
int i = 1;
while (itr)
{
if (i == (m - 1))
p_pre = itr;
if (i == m)
p = itr;
if (i == n)
q = itr;
if (i == n + 1)
q_next = itr;
itr = itr->next;
i++;
}
/*反转p到q之间的元素,head_和tail为反转后的头和尾*/
ListNode* head_, *tail_, *it_;
stack<ListNode*>ln_stk;
it_ = p;
while (it_ != q_next)
{
ln_stk.push(it_);
it_ = it_->next;
}
it_ = ln_stk.top();
head_ = it_;
ln_stk.pop();
while (!ln_stk.empty())
{
it_->next = ln_stk.top();
it_ = it_->next;
ln_stk.pop();
}
it_->next = NULL;
tail_ = it_;
/*反转p到q之间的元素,head_和tail为反转后的头和尾*/
if (p_pre != NULL)
{
p_pre->next = head_;
}
else head = head_;
if (q_next != NULL)
{
tail_->next = q_next;
}
return head;
}