225. Implement Stack using Queues

https://leetcode.com/problems/implement-stack-using-queues/description/

solution

class MyStack:
    def __init__(self):
        self.q1 = []
        self.q2 = []        

    def push(self, x: int) -> None:
        self.q1.append(x)        

    def pop(self) -> int:
        if self.empty():
            return None
        
        for i in range(len(self.q1) - 1):
            self.q2.append(self.q1.pop(0))
        self.q1, self.q2 = self.q2, self.q1
        return self.q2.pop(0)        

    def top(self) -> int:
        if self.q1:
            return self.q1[-1]        

    def empty(self) -> bool:
        if self.q1:
            return False
        else:
            return True

时间复杂度:O() 空间复杂度:O()

Last updated