方法一:使用栈交换需要反转的数字
#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; }
方法二:直接反转需要反转的部分
#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背包没时间做,我恨!