232. Implement Queue using Stacks

https://leetcode.com/problems/implement-queue-using-stacks/

solution

class MyQueue:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []        

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

    def pop(self) -> int:        
        if self.stack2:
            return self.stack2.pop()
        elif self.stack1:
            while self.stack1:
                self.stack2.append(self.stack1.pop(-1))
            return self.stack2.pop(-1)  
        else:
            return

    def peek(self) -> int:
        if self.stack2:
            return self.stack2[-1]
        elif self.stack1:
            return self.stack1[0]
        else:
            return       

    def empty(self) -> bool:
        if len(self.stack1) + len(self.stack2) > 0:
            return False
        else:
            return True

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

Last updated