Skip to content

Latest commit

 

History

History
105 lines (91 loc) · 2.53 KB

File metadata and controls

105 lines (91 loc) · 2.53 KB

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Related Topics:
Stack, Design

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/implement-stack-using-queues
// Author: github.com/lzl124631x
// Time: O(N) for push, O(1) for others
// Space: O(1)
class MyStack {
private:
  queue<int> q;
public:
  MyStack() {}
  void push(int x) {
    q.push(x);
    for (int i = 0; i < q.size() - 1; ++i) {
      q.push(q.front());
      q.pop();
    }
  }
  int pop() {
    int val = q.front();
    q.pop();
    return val;
  }
  int top() {
    return q.front();
  }
  bool empty() {
    return q.empty();
  }
};

Solution 2.

// OJ: https://leetcode.com/problems/implement-stack-using-queues/
// Author: github.com/lzl124631x
// Time: O(N) for pop, O(1) for others
// Space: O(1)
class MyStack {
    queue<int> q;
    int t;
public:
    MyStack() {}
    void push(int x) {
        q.push(x);
        t = x;
    }
    int pop() {
        int n = q.size();
        while (--n) {
            int val = q.front();
            if (n == 1) t = val;
            q.push(val);
            q.pop();
        }
        int val = q.front();
        q.pop();
        return val;
    }
    int top() {
        return t;
    }
    bool empty() {
        return !q.size();
    }
};