题目:元素出栈、入栈顺序的合法性。如:入栈的序列(1,2,3,4,5),出栈序列为(4,5,3,2,1),则合法。入栈的序列(1,2,3,4,5),出栈序列为(4,5,2,3,1),则不合法。
这道题我们可以创建两个栈(感觉有点类似两个栈实现一个队列),需要几个数字放在前面即把S1的栈顶元素取几个放在S2里面即可。
出栈时候先判断S2是否为空,不为空则从S2栈顶元素逐个取出,再从S1中取出剩下的元素即可。
所以上图出栈顺序为4,5,3,2,1符合题目要求。
下面给出代码:
#include <iostream>
#include <stack>
#include <assert.h>
using namespace std;
typedef int T;
class Stack
{
public:
Stack()
{}
~Stack()
{}
void Push(T data)
{
s1.push(data);
}
void Pop()
{
while (!s2.empty())
{
cout << "s2.pop(" << s2.top() << ")" << endl;
s2.pop();
}
if (!s1.empty())
{
cout << "s1.pop(" << s1.top() << ")" << endl;
s1.pop();
}
}
void NumReverse(int x)
{
if (x > s1.size() && x < 0)
return;
while (x)
{
T temp = s1.top();
if (!s1.empty())
{
s1.pop();
s2.push(temp);
}
--x;
}
}
private:
stack<T> s1;
stack<T> s2;
};
int main()
{
Stack s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
s.NumReverse(2);
s.Pop();
s.Pop();
s.Pop();
s.Pop();
return 0;
}
实现结果为: