225. Implement Stack using Queues

Implement Stack using Queues - LeetCode

Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty). Implement the MyStack class:

void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.

  • code O(n)
class MyStack:

    def __init__(self):
        self.q = collections.deque()

    def push(self, x):
        self.q.append(x)
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())
        
    def pop(self):
        return self.q.popleft()

    def top(self):
        return self.q[0]
    
    def empty(self):
        return not self.q
  • code nested q
class MyStack:

    def __init__(self):
        self.queue = None

    def push(self, x):
        q = collections.deque()
        q.append(x)
        q.append(self.queue)
        self.queue = q

    def pop(self):
        num = self.queue.popleft()
        self.queue = self.queue.popleft()
        return num

    def top(self):
        return self.queue[0]

    def empty(self):
        return not self.queue