题目地址:
https://leetcode.com/problems/implement-stack-using-queues/
用队列实现栈。
思路是,push的时候就入队,并将队头的 n − 1 n-1 n−1个元素全offer到队尾;peek或者pop的时候直接看队头。代码如下:
class MyStack {
public:
queue<int> q;
MyStack() {}
void push(int x) {
q.push(x);
for (int i = q.size() - 1; i; i--) {
q.push(q.front());
q.pop();
}
}
int pop() {
int t = q.front();
q.pop();
return t;
}
int top() { return q.front(); }
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();
*/
时间复杂度:peek或pop: O ( 1 ) O(1) O(1),push: O ( n ) O(n) O(n)。