用队列实现栈
**题目描述:**请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
思路:我们可以使用两个队列,一个队列当作存储栈的主队列,另外一个作为辅助队列,用来帮助主队列实现栈的功能。
class MyStack {
public:
queue<int> queue1;
queue<int> queue2;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
//先将要插入元素插进辅助队列中
queue2.push(x);
//当主队列不为空时,将主队列中的所有元素插入辅助队列中,这样可以保证主队列中的之前的元素都在要插入元素的后面。即使主队列为空时,直接交换两个队列即可。
while (!queue1.empty()) {
queue2.push(queue1.front());
queue1.pop();
}
swap(queue1, queue2);
}
/** Removes the element on top of the stack and returns that element. */
//弹出栈中顶的元素(或者新插入的元素)——》新插入的元素在主队列的头部。即返回主队了的头部的数据即可。
int pop() {
int r = queue1.front();
queue1.pop();
return r;
}
/** Get the top element. */
int top() {
int r = queue1.front();
return r;
}
/** Returns whether the stack is empty. */
//直接判断主队列是否为空即可。
bool empty() {
return queue1.empty();
}
};
用栈实现队列
**题目描述:**请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
解题思路:
不管在执行什么操作时,一定要保证其中的一个栈为空,比如(插入元素时,必须保证出栈的这个栈为空)
class MyQueue {
public:
stack<int>in_stack;//主栈
stack<int>out_stack;//辅助栈
MyQueue() {
//初始化
while(!in_stack.empty())
{
in_stack.pop();
}
while(!out_stack.empty())
{
out_stack.pop();
}
}
void push(int x) {
while(!out_stack.empty())
{
in_stack.push(out_stack.top());
out_stack.pop();
}
in_stack.push(x);
}
int pop() {
while(!in_stack.empty())
{
out_stack.push(in_stack.top());
in_stack.pop();
}
int x=out_stack.top();
out_stack.pop();
return x;
}
int peek() {
while(!in_stack.empty())
{
out_stack.push(in_stack.top());
in_stack.pop();
}
return out_stack.top();
}
bool empty() {
return in_stack.empty()&&out_stack.empty();
}
};