leetcode 链接:225. 用队列实现栈

题目

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。
实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

  • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。
  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

解答 & 代码

解法一:一个队列实现

入队操作前,先记录当前队列的 size,将当前元素入队,然后将前面的 size 个元素依次出队再入队
因此,push 的时间复杂度为 O(N),其余操作的时间复杂度为 O(1)

  1. class MyStack {
  2. private:
  3. queue<int> q;
  4. public:
  5. /** Initialize your data structure here. */
  6. MyStack() {
  7. }
  8. /** Push element x onto stack. */
  9. void push(int x) {
  10. int size = q.size();
  11. q.push(x); // 将当前元素插入队尾
  12. // 将前面的元素依次出队再入队
  13. for(int i = 0; i < size; ++i)
  14. {
  15. q.push(q.front());
  16. q.pop();
  17. }
  18. }
  19. /** Removes the element on top of the stack and returns that element. */
  20. int pop() {
  21. int top = q.front();
  22. q.pop();
  23. return top;
  24. }
  25. /** Get the top element. */
  26. int top() {
  27. return q.front();
  28. }
  29. /** Returns whether the stack is empty. */
  30. bool empty() {
  31. return q.size() == 0;
  32. }
  33. };
  34. /**
  35. * Your MyStack object will be instantiated and called as such:
  36. * MyStack* obj = new MyStack();
  37. * obj->push(x);
  38. * int param_2 = obj->pop();
  39. * int param_3 = obj->top();
  40. * bool param_4 = obj->empty();
  41. */

执行结果:

执行结果:通过

执行用时:0 ms, 在所有 C++ 提交中击败了 100.00% 的用户
内存消耗:6.7 MB, 在所有 C++ 提交中击败了 45.05% 的用户