题意描述:
使用队列实现栈的下列操作:
- push(x) – 元素 x 入栈
- pop() – 移除栈顶元素
- top() – 获取栈顶元素
- empty() – 返回栈是否为空
注意:
- 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
- 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
- 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
解题思路:
Alice: 这种题目说难也不难,但是第一次见到,可能还要想一下。
Bob: 对啊,我觉得这种代码量小,容易描述,又有一点技巧的题很适合拿来面试啊。
Alice: 我最开始想的是让队列尾部做栈顶,用一个实例变量维护队列尾部也就是栈顶的元素,然后入栈很方便,出栈的话,我先把队列前面 k-1 个元素出队,存起来,然后剩最后一个元素,这时候出队和出栈就是一样的,也不用管什么方向了,然后再把前 k-1 个元素入队。临时存的时候也用队列。
Bob: 不错不错,不过,你每次出栈都要用到一个队列,用完之后就销毁了,这样频繁的实例化一个队列是不是比较耗时啊。
Alice: 对啊,所以我看到有人,直接用了两个队列来做,q2总是空的状态,q1 的队头表示栈顶,这样出栈很方便。入栈的时候,先把元素放到 q2, 然后将q1 中的元素从队尾依次放到q2里面,最后交换两个引用的指向,就维护了栈顶永远在q1的队头。
Bob: 哈哈哈,这样也不错,不过上面的两个队列完全可以变成一个,只有一个q1也可以,还是队头表示栈顶,这样出栈很方便,入栈的时候,先把元素放到队尾,然后将前面 k-1 个元素依次放到队尾,这样入栈的元素就放到了队头,也就是栈顶。
Alice: 😎😎
代码:
Python 方法一: 用 list 模拟栈, list 本身就可以当做栈来用的
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.data.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
tmp = self.data[-1]
self.data.pop(-1)
return tmp
def top(self) -> int:
"""
Get the top element.
"""
return self.data[-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self.data) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
Java 方法一: 入栈 O(1) 出栈 O(n) 两个队列
class MyStack {
private Queue<Integer> data;
private int last;
/** Initialize your data structure here. */
public MyStack() {
data = new LinkedList<Integer>();
last = 0;
}
/** Push element x onto stack. */
public void push(int x) {
data.offer(x);
last = x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
Queue<Integer> helper = new LinkedList<Integer>();
while(data.size() > 1){
helper.offer(data.poll());
}
int ret = data.poll();
while(helper.isEmpty() == false){
last = helper.poll();
data.offer(last);
}
return ret;
}
/** Get the top element. */
public int top() {
return last;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return data.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();
*/
Java 方法二: 入栈 O(n) 出栈O(1), 队列头部是栈顶
class MyStack {
private Queue<Integer> q1;
private Queue<Integer> q2;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<Integer>();
q2 = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
q2.offer(x);
while(q1.isEmpty() == false){
q2.offer(q1.poll());
// 将x 压入栈顶,也就是队列头部
}
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.poll();
}
/** 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();
*/
Java 方法三: 一个队列,队列头部是栈顶,入栈O(n),出栈O(1)
class MyStack {
private Queue<Integer> data;
/** Initialize your data structure here. */
public MyStack() {
data = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
int steps = data.size();
// 前面有几个元素
data.offer(x);
// 将前面的元素调整到队列尾部等于将队列尾部的元素放到队列头部,即栈顶。
for(int i=0; i<steps; ++i){
data.offer(data.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return data.poll();
}
/** Get the top element. */
public int top() {
return data.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return data.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();
*/
易错点:
- 使用实例变量维护栈顶元素的时候,出栈的操作后要记得更新栈顶元素的值。
总结:
- Python 写起来真的很快,不过可能不太适合用来学习算法。