29.栈的push、pop序列
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
分析:
想要判断pop序列是不是和push序列对应,只要按照push序列和pop序列指定的顺序完成push和pop操作,然后看栈能否恰好在push和pop操作都结束后到达空的状态,若能,返回true。
若pop顺序正确,pop序列中的每个元素在push过程中总会有位于栈顶的时候,若在push结束时pop序列中的元素未能找到和其相同的栈顶元素,说明pop顺序有误,返回false
代码:
#include<stack>
#include<iostream>
using namespace std;
namespace MS100P_29
{
bool isPopOfPush(const int *pushSeq, const int *popSeq, int length)
{
stack<int> s;
int i = 0, j = 0;
while (i != length || !s.empty())
{
if (i != length&&s.empty()) s.push(pushSeq[i++]);
while (s.top() != popSeq[j])
{
if (i == length) return false;
s.push(pushSeq[i++]);
}
s.pop();
j++;
}
return true;
}
void test()
{
int pushSeq[] = { 1, 2, 3, 4, 5 };
int popSeq1[] = { 1, 2, 5, 3, 4 };
int popSeq2[] = { 2, 1, 3, 4, 5 };
int popSeq3[] = { 5, 3, 1, 2, 5 };
int popSeq4[] = { 5, 4, 3, 2, 1 };
int popSeq5[] = { 4, 2, 3, 1, 5 };
int popSeq6[] = { 3, 4, 2, 1, 5 };
cout << isPopOfPush(pushSeq, popSeq1, 5) << endl;
cout << isPopOfPush(pushSeq, popSeq2, 5) << endl;
cout << isPopOfPush(pushSeq, popSeq3, 5) << endl;
cout << isPopOfPush(pushSeq, popSeq4, 5) << endl;
cout << isPopOfPush(pushSeq, popSeq5, 5) << endl;
cout << isPopOfPush(pushSeq, popSeq6, 5) << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
MS100P_29::test();
return 0;
}
测试的几组数据都没有问题,但是不是很确定程序完全正确,如有错误,欢迎大家指正。