剑指 Offer 31. 栈的压入、弹出序列
题目描述
C++解法
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
bool validateStackSequences(vector<int>& pushed, vector<int>& popped)
{
if (pushed.size() == 0)
return true;
int size = pushed.size();
int count = 0;
stack<int>st;
for (int i = 0;i < size;i++)
{
st.push(pushed[i]);
while (!st.empty() && st.top() == popped[count])
{
st.pop();
count++;
}
}
if (st.empty())
return true;
else
return false;
}
void print(bool result)
{
if (result)
cout << "是正确的出栈序列" << endl;
else
cout << "不是正确的出栈序列" << endl;
}
void test()
{
cout << "test" << endl;
int n;
cout << "请输入入栈序列长度" << endl;
cin >> n;
vector<int>pushed(n);
vector<int>poped(n);
for (int i = 0;i < n;i++)
{
cin >> pushed[i];
}
for (int i = 0;i < n;i++)
{
cin >> poped[i];
}
bool result = validateStackSequences(pushed, poped);
if (result)
cout << "是正确的出栈序列"<<endl;
else
cout << "不是正确的出栈序列"<< endl;
}
void Test1()
{
cout << "test1" << endl;
const int nLength = 5;
vector<int> push= { 1, 2, 3, 4, 5 };
vector<int> pop = { 4, 5, 3, 2, 1 };
print(validateStackSequences(push, pop));
}
void Test2()
{
cout << "test2" << endl;
const int nLength = 5;
vector<int> push = { 1, 2, 3, 4, 5 };
vector<int> pop = { 3, 5, 4, 2, 1 };
print(validateStackSequences(push, pop));
}
void Test3()
{
cout << "test3" << endl;
const int nLength = 1;
vector<int> push = { 1 };
vector<int> pop = { 2 };
print(validateStackSequences(push, pop));
}
void Test4()
{
cout << "test4" << endl;
const int nLength = 1;
vector<int> push = { 1 };
vector<int> pop = { 1 };
print(validateStackSequences(push, pop));
}
void Test5()
{
cout << "test4" << endl;
const int nLength = 0;
vector<int> push ;
vector<int> pop ;
print(validateStackSequences(push, pop));
}
int main()
{
test();
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}
结果