日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

《剑指offer》第三十一题(栈的压入、弹出序列)

發布時間:2024/1/17 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《剑指offer》第三十一题(栈的压入、弹出序列) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 面試題31:棧的壓入、彈出序列 // 題目:輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是 // 否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1、2、3、4、 // 5是某棧的壓棧序列,序列4、5、3、2、1是該壓棧序列對應的一個彈出序列,但 // 4、3、5、1、2就不可能是該壓棧序列的彈出序列。 #include <iostream> #include <stack>bool IsPopOrder(const int* pPush, const int* pPop, int nLength) {bool bPossible = false;if (pPush != nullptr && pPop != nullptr && nLength > 0){const int* pNextPush = pPush;const int* pNextPop = pPop;std::stack<int> stackData;while (pNextPop - pPop < nLength){// 當輔助棧的棧頂元素不是要彈出的元素// 先壓入一些數字入棧while (stackData.empty() || stackData.top() != *pNextPop){// 如果所有數字都壓入輔助棧了,退出循環if (pNextPush - pPush == nLength)break;stackData.push(*pNextPush);pNextPush++;}if (stackData.top() != *pNextPop)//完了,不匹配break;stackData.pop();//彈出這個匹配的pNextPop++;//檢測下一個要pop的 }if (stackData.empty() && pNextPop - pPop == nLength)//檢測條件bPossible = true;}return bPossible; }// ====================測試代碼==================== void Test(const char* testName, const int* pPush, const int* pPop, int nLength, bool expected) {if (testName != nullptr)printf("%s begins: ", testName);if (IsPopOrder(pPush, pPop, nLength) == expected)printf("Passed.\n");elseprintf("failed.\n"); }void Test1() {const int nLength = 5;int push[nLength] = { 1, 2, 3, 4, 5 };int pop[nLength] = { 4, 5, 3, 2, 1 };Test("Test1", push, pop, nLength, true); }void Test2() {const int nLength = 5;int push[nLength] = { 1, 2, 3, 4, 5 };int pop[nLength] = { 3, 5, 4, 2, 1 };Test("Test2", push, pop, nLength, true); }void Test3() {const int nLength = 5;int push[nLength] = { 1, 2, 3, 4, 5 };int pop[nLength] = { 4, 3, 5, 1, 2 };Test("Test3", push, pop, nLength, false); }void Test4() {const int nLength = 5;int push[nLength] = { 1, 2, 3, 4, 5 };int pop[nLength] = { 3, 5, 4, 1, 2 };Test("Test4", push, pop, nLength, false); }// push和pop序列只有一個數字 void Test5() {const int nLength = 1;int push[nLength] = { 1 };int pop[nLength] = { 2 };Test("Test5", push, pop, nLength, false); }void Test6() {const int nLength = 1;int push[nLength] = { 1 };int pop[nLength] = { 1 };Test("Test6", push, pop, nLength, true); }void Test7() {Test("Test7", nullptr, nullptr, 0, false); }int main(int argc, char* argv[]) {Test1();Test2();Test3();Test4();Test5();Test6();Test7();system("pause");return 0; }

?

轉載于:https://www.cnblogs.com/CJT-blog/p/10492473.html

總結

以上是生活随笔為你收集整理的《剑指offer》第三十一题(栈的压入、弹出序列)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。