Implement Stack using Queues

Key Idea

Solution

class MyStack:
    # You can only append to back and read from front
    def __init__(self):
        self.queue = []

    def push(self, x: int) -> None:
        # Append to back
        self.queue.append(x)
        # Read from the front till -1
        # Note since we iterate TILL -1, means we keep it "last" at new list
        for i in range(len(self.queue) -1):
            self.queue.append(self.queue.pop(0))

    def pop(self) -> int:
        # Last in first Out
        return self.queue.pop(0)        

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

    def empty(self) -> bool:
        if not self.queue:
            return True
        return False


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

Complexity