转自:http://blog.csdn.net/wangyl_gain/article/details/50449318------数据结构01--栈
题目:
用例程序会进行一系列入栈和出栈的混合操作。入栈操作会将整数0-9顺序压入栈中,判断出栈顺序是否正确。
例如:
- 入栈: 0- 1- 2- 3- 4- 5- 6- 7- 8- 9
- 出栈:4- 3 -2- 1 -0- 9 -8 -7- 6 -5 (正确)
- 出栈:4 -6 -8- 7- 5- 3- 2- 9 -0- 1(错误)
代码如下:
#include<iostream>
#include<stack>
using namespace std;
bool stackCanGenerated(const int *pushS,const int *popS)
{
stack<int> s;
int i,j;
for(i = 0,j = 0;i < 10;i++)
{
s.push(pushS[i]);
for(;!s.empty() && s.top() == popS[j];j++)
{
s.pop();
}
}
if(s.empty())
return true;
else
return false;
}
int main(void)
{
int pushSeq[10];
int popSeq[10];
for(int i = 0;i < 10;i++)
{
pushSeq[i] = i;
}
for(int i = 0;i < 10;i++)
{
int t;
cin >> t;
popSeq[i] = t;
}
cout << "ret-->" << stackCanGenerated(pushSeq,popSeq) << endl;
return 0;
}