【面试题022】栈的压入、弹出序列
如果所有的数字都压入栈了仍然没有找到下一个弹出的数字,
StackPushPop.cpp:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
#include <iostream>
#include <cstdio> #include <stack> using namespace std; /* * pPush 是插入队列的顺序 * pPop 是弹出的顺序 * nLength是pPush的长度 */ bool IsPopOrder(const int *pPush, const int *pPop, int nLength) { bool bPossible = false; /*不满足条件的,直接返回false*/ if(pPush != NULL && pPop != NULL && nLength > 0) { const int *pNextPush = pPush; const int *pNextPop = pPop; std::stack<int> stackData; /*pNextPop 一直往移动,直到移动到末尾*/ 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 ++; } /*如果辅助栈为空,而且弹出序列已经移动到末尾了*/ if(stackData.empty() && pNextPop - pPop == nLength) { bPossible = true; } } return bPossible; } // ====================测试代码==================== void Test(char *testName, const int *pPush, const int *pPop, int nLength, bool expected) { if(testName != NULL) printf("%s begins: ", testName); if(IsPopOrder(pPush, pPop, nLength) == expected) printf("Passed. "); else printf("failed. "); } 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] = {4, 3, 5, 1, 2}; Test("Test2", push, pop, nLength, false); } int main() { Test1(); Test2(); return 0; } |
运行结果:
Test1 begins: Passed.
Test2 begins: Passed.
Makefile:
1
2 3 4 5 6 7 8 9 10 11 12 |
.PHONY:clean
CPP=g++ CFLAGS=-Wall -g BIN=test OBJS=StackPushPop.o LIBS= $(BIN):$(OBJS) $(CPP) $(CFLAGS) $^ -o $@ $(LIBS) %.o:%.cpp $(CPP) $(CFLAGS) -c $< -o $@ clean: rm -f *.o $(BIN) |