题目描述:
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
思路(两个队列):
1、队列的特点是先进先出,栈的特点是后进先出;
2、利用两个队列,q1模拟栈数据结构,q2用来暂存数据;
3、为了保证栈后进先出的特点,那么先入队列的需要一直保持在队尾,后入队的需要插入到队首;
4、因此每次有元素value入栈,就先将元素插入队列q2中,然后将q1中元素依次出队,插入q2中,这样,新插入的元素value就在q2的队首,然后将q1和q2置换;
5、出栈的时候,只需要将q1中的队首出队即可;
Java解法:
class MyStack {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();
private int top;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<Integer>();
q2 = new LinkedList<Integer>();
top = 0;
}
/** Push element x onto stack. */
public void push(int x) {
q2.add(x);
top = x;
while(!q1.isEmpty())
{
q2.add(q1.remove());
}
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int ans = top;
q1.remove();
if(!q1.isEmpty())
{
top = q1.peek();
}
return ans;
}
/** Get the top element. */
public int top() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
思路(一个队列):
1、根据队列的特点,每次入队,新元素value都会排在队尾;
2、为了符合栈后进先出的特点,就需要新元素value排在队首;
3、在新元素入队之后,需要将前面的元素依次出队,再入队,排在新元素之后。
Java解法:
class MyStack {
private Queue<Integer> q1 = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
q1.add(x);
int size = q1.size();
while(size > 1)
{
q1.add(q1.remove());
size--;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.remove();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues








网友评论