leetcode 92 反轉鏈表 II c++實現

分爲三步

  • 用四個指針,分別指向反轉位置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;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章