vivo 部分链表反转
Posted ccxikka
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vivo 部分链表反转相关的知识,希望对你有一定的参考价值。
方法一:使用栈交换需要反转的数字
#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背包没时间做,我恨!
以上是关于vivo 部分链表反转的主要内容,如果未能解决你的问题,请参考以下文章
2021-09-11:给你一个32位的有符号整数x,返回将x中的数字部分反转后的结果。反转后整数超过 32 位的有符号整数的范围就返回0,假设环境不允许存储 64 位整数(有符号或无符号)。(代码片段