方法一:使用棧交換須要反轉的數字ios
#include <iostream> #include <stack> #include "list.h" using namespace std; void partreverse(ListNode* phead, int m, int n) { int count = 1; ListNode* p = phead; stack<ListNode*> s1; if (m < 1 || n < 1) return; if (m > n) {//保證m小於n int temp = m; m = n; n = temp; } if (m == n)//二者相等不交換直接返回 return; while (count < m && p != nullptr) { count++; p = p->m_pNext; } ListNode* start = p; int estart = m + (n - m) / 2 + 1; while (count <n && p != nullptr) { count++; p = p->m_pNext; if (count >= estart) { if (p != nullptr) s1.push(p);//後半部分進棧 else return;//超出長度直接返回 } } while (!s1.empty()) {//依次交換 ListNode* cur = s1.top(); int temp = cur->m_nValue; cur->m_nValue = start->m_nValue; start->m_nValue = temp; s1.pop(); start = start->m_pNext; } return; } void Test1() { ListNode* pNode1 = CreateListNode(1); ListNode* pNode2 = CreateListNode(2); ListNode* pNode3 = CreateListNode(3); ListNode* pNode4 = CreateListNode(4); ListNode* pNode5 = CreateListNode(5); ConnectListNodes(pNode1, pNode2); ConnectListNodes(pNode2, pNode3); ConnectListNodes(pNode3, pNode4); ConnectListNodes(pNode4, pNode5); PrintList(pNode1); partreverse(pNode1, 2, 4); PrintList(pNode1); } int main(int argc, char* argv[]) { Test1(); return 0; }
方法二:直接反轉須要反轉的部分spa
#include <iostream> #include "list.h" using namespace std; void partreverse(ListNode* phead, int m, int n) { int count = 1; ListNode* p = phead; if (m < 1 || n < 1) return; if (m > n) {//保證m小於n int temp = m; m = n; n = temp; } if (m == n)//二者相等不交換直接返回 return; while (count < m-1 && p != nullptr) { count++; p = p->m_pNext; } ListNode* prev = p, *start = phead, *end = nullptr, *next = nullptr; if (m == 1) prev = nullptr; if (prev != nullptr) start = prev->m_pNext; p = start; for (count = m; count < n && p != nullptr;) { count++; p = p->m_pNext; } end = p; if (end != nullptr) next = end->m_pNext; else return;//end爲nullptr,超出鏈表長度 if(prev !=nullptr) prev->m_pNext = end;//prev指向反轉後的鏈表頭 end->m_pNext = nullptr; ListNode* rprve = start, *rcur = start->m_pNext, *rnext = rcur->m_pNext; while (rcur != end) {//指定範圍內的鏈表反轉 rcur->m_pNext = rprve; rprve = rcur; rcur = rnext; if (rnext != nullptr) rnext = rnext->m_pNext; } rcur->m_pNext = rprve; start->m_pNext = next; if (prev == nullptr) phead = end;//鏈表頭被反轉 PrintList(phead); return; } void Test1() { ListNode* pNode1 = CreateListNode(1); ListNode* pNode2 = CreateListNode(2); ListNode* pNode3 = CreateListNode(3); ListNode* pNode4 = CreateListNode(4); ListNode* pNode5 = CreateListNode(5); ConnectListNodes(pNode1, pNode2); ConnectListNodes(pNode2, pNode3); ConnectListNodes(pNode3, pNode4); ConnectListNodes(pNode4, pNode5); PrintList(pNode1); partreverse(pNode1, 1, 5); //PrintList(pNode1); } int main(int argc, char* argv[]) { Test1(); return 0; }
前面花太多時間致使後面的送分題01揹包沒時間作,我恨!code