leetcode 链接:225. 用队列实现栈
题目
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x)将元素 x 压入栈顶。int pop()移除并返回栈顶元素。int top()返回栈顶元素。boolean empty()如果栈是空的,返回true;否则,返回false。
注意:
- 你只能使用队列的基本操作 —— 也就是
push to back、peek/pop from front、size和is empty这些操作。 - 你所使用的语言也许不支持队列。 你可以使用
list(列表)或者deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
解答 & 代码
解法一:一个队列实现
入队操作前,先记录当前队列的 size,将当前元素入队,然后将前面的 size 个元素依次出队再入队
因此,push 的时间复杂度为 O(N),其余操作的时间复杂度为 O(1)
class MyStack {private:queue<int> q;public:/** Initialize your data structure here. */MyStack() {}/** Push element x onto stack. */void push(int x) {int size = q.size();q.push(x); // 将当前元素插入队尾// 将前面的元素依次出队再入队for(int i = 0; i < size; ++i){q.push(q.front());q.pop();}}/** Removes the element on top of the stack and returns that element. */int pop() {int top = q.front();q.pop();return top;}/** Get the top element. */int top() {return q.front();}/** Returns whether the stack is empty. */bool empty() {return q.size() == 0;}};/*** 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();*/
执行结果:
执行结果:通过
执行用时:0 ms, 在所有 C++ 提交中击败了 100.00% 的用户
内存消耗:6.7 MB, 在所有 C++ 提交中击败了 45.05% 的用户
