下面两幅图分别是栈和队列的简单介绍:
1.入栈(push)
入栈时,给其中一个队列入相同的数据。
2.出栈(pop)
queue1出队一个数据,将这个数据入队进queue2,直至queue1.size()==1出队结束。
3.取栈顶(top)
栈顶元素为queue1.head的值。
代码实现:(代码中head = back,tail = front)
#include<iostream>
#include<queue>
using namespace std;
//1.用两个队列实现一个栈
template<class T>
class Stack
{
private:
queue<T> queue1;
public:
void push(T x)
{
queue1.push(x);
}
void pop()
{
queue<T> queue2;//中间局部变量,借用他删除队头元素。
while (queue1.size() > 1)
{
queue2.push(queue1.front());
queue1.pop();
}
queue1 = queue2;
}
T& top()
{
return queue1.back();
}
};
int main()
{
Stack<int> st;
st.push(1);
st.push(2);
st.pop();
st.push(3);
st.push(4);
st.pop();
cout << st.top() << endl;;
system("pause");
return 0;
}