《剑指offer》第三十一题(栈的压入、弹出序列)
生活随笔
收集整理的這篇文章主要介紹了
《剑指offer》第三十一题(栈的压入、弹出序列)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
// 面試題31:棧的壓入、彈出序列
// 題目:輸入兩個整數(shù)序列,第一個序列表示棧的壓入順序,請判斷第二個序列是
// 否為該棧的彈出順序。假設(shè)壓入棧的所有數(shù)字均不相等。例如序列1、2、3、4、
// 5是某棧的壓棧序列,序列4、5、3、2、1是該壓棧序列對應(yīng)的一個彈出序列,但
// 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){// 當(dāng)輔助棧的棧頂元素不是要彈出的元素// 先壓入一些數(shù)字入棧while (stackData.empty() || stackData.top() != *pNextPop){// 如果所有數(shù)字都壓入輔助棧了,退出循環(huán)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序列只有一個數(shù)字
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;
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/CJT-blog/p/10492473.html
總結(jié)
以上是生活随笔為你收集整理的《剑指offer》第三十一题(栈的压入、弹出序列)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 应用的生命周期各个程序运行状态时代理的回
- 下一篇: 017 矩阵中的路径