算法
(队列,栈) O(n)
我们用一个队列来存储栈中元素。对于栈中的四种操作:
push(x) – 直接入队;
pop() – 即需要弹出队尾元素。我们先将队首元素弹出并插入队尾,循环 n−1次,n是队列长度。此时队尾元素已经在队首了,直接将其弹出即可;
top() – 即返回队尾元素。同理,我们先将队首元素弹出并插入队尾,循环 n−1次,n是队列长度。此时队尾元素已经在队首了,直接将其返回。不要忘记将其弹出并插入队尾,恢复队列原状;
empty() – 返回队列是否为空;
时间复杂度分析:push() 和 empty() 均只有一次操作,时间复杂度是 O(1),pop() 和 top() 需要循环 n 次,所以时间复杂度是 O(n)。
class MyStack {
public:/** Initialize your data structure here. */queue<int> q;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() {int sz = q.size();while (sz -- > 1) q.push(q.front()), q.pop();int x = q.front();q.pop();return x;}/** Get the top element. */int top() {int sz = q.size();while (sz -- > 1) q.push(q.front()), q.pop();int x = q.front();q.pop(), q.push(x);return x;}/** Returns whether the stack is empty. */bool empty() {return q.empty();}
};/*** 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();* bool param_4 = obj.empty();*/