轉自: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;
}