栈的压入、弹出序列

来源:互联网 发布:字母设计软件 编辑:程序博客网 时间:2024/05/23 18:56

//输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。//假设压入栈的所有数字均不相等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是//该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。#include "iostream"#include "stack"using namespace std;bool IsPopOrder(const int *pPush, const int *pPop, int nLength){stack<int> simulationStack;int iPush = 0;int iPop = 0;while (iPush < nLength && iPop < nLength){if (pPush[iPush] != pPop[iPop]){if (!simulationStack.empty() && simulationStack.top() == pPop[iPop]){cout << "pop: " << pPop[iPop] << endl;simulationStack.pop();iPop++;}else{cout << "push: " << pPush[iPush] << endl;simulationStack.push(pPush[iPush]);iPush++;}}else{cout << "push and pop: " << pPush[iPush] << endl;iPush++;iPop++;}}while (iPop < nLength){if (!simulationStack.empty() && simulationStack.top() == pPop[iPop]){cout << "pop: " << pPop[iPop] << endl;simulationStack.pop();iPop++;}elsereturn false;}return true;}void test(){int a[] = { 1, 2, 3, 4, 5 };int b[] = { 4, 5, 3, 2, 1 };int c[] = { 5, 4, 3, 2, 1 };cout << IsPopOrder(a, b, sizeof(a) / sizeof(int)) << endl;cout << IsPopOrder(a, c, sizeof(a) / sizeof(int)) << endl;}int main(){test();return 0;}
其实就是模拟出栈入栈的过程。两个数组一个栈之间的关系,人脑思考判断的过程就是程序的流程。


0 0
原创粉丝点击