【经典算法题】用队列实现栈
Leetcode 0225 用队列实现栈
题目描述:Leetcode 0225 用队列实现栈
分析
-
本题的考点:设计。
-
使用两个队列
q, w
,q
用于存储元素,w
是缓存队列。 -
每次插入元素时,向
q
中插入元素; -
删除栈顶元素时,可以先将队列中前
q.size()-1
个元素存储到缓存队列w
中,最后将q
中剩余的一个元素缓存到临时变量t
中,然后删除q
中最后一个元素,最后将w
中的元素再次放入q
中即可; -
返回栈顶元素的操作和删除类似;
-
栈是否为空只需要看
q
是否为空即可。
代码
- C++
class MyStack {
public:
queue<int> q, w;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while (q.size() > 1) w.push(q.front()), q.pop();
int t = q.front(); q.pop();
while (w.size()) q.push(w.front()), w.pop();
return t;
}
/** Get the top element. */
int top() {
while (q.size() > 1) w.push(q.front()), q.pop();
int t = q.front(); q.pop();
while (w.size()) q.push(w.front()), w.pop();
q.push(t);
return t;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
- Java
class MyStack {
Queue<Integer> q = new LinkedList<>(), w = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while (q.size() > 1) w.add(q.remove());
int t = q.remove();
while(w.size() != 0) q.add(w.remove());
return t;
}
/** Get the top element. */
public int top() {
while (q.size() > 1) w.add(q.remove());
int t = q.remove();
while(w.size() != 0) q.add(w.remove());
q.add(t);
return t;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}
时空复杂度分析
-
时间复杂度:
top
和pop
操作和栈中元素个数成正比,其余操作是 O ( 1 ) O(1) O(1)的。 -
空间复杂度: O ( n ) O(n) O(n),
n
为栈中元素个数。