用队列实现栈
使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
解:用两个队列实现栈
stl中队列的使用:
#include<queue>// 队列
queue<int> q; //参数是数据类型,这是队列的定义方式
q.empty()// 如果队列为空返回true,否则返回false
q.size() // 返回队列中元素的个数
q.pop() //删除队列首元素但不返回其值
q.front() // 返回队首元素的值,但不删除该元素
q.push(X) //在队尾压入新元素 ,X为要压入的元素
q.back() //返回队列尾元素的值,但不删除该元素
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
input.push(x);
q2q(output,input);
std::swap(input,output);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int res=output.front();
output.pop();
return res;
}
/** Get the top element. */
int top() {
return output.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return output.empty();
}
private:
queue<int> input;
queue<int> output;
void q2q(queue<int> &a,queue<int>&b)
{
while(!a.empty())
{
b.push(a.front());
a.pop();
}
}
};