【剑指】用两个栈实现队列

一个栈负责append,一个栈负责push。push之前如果stack2为空,stack1不为空,就把stack1都pop到stack2。

class CQueue:

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

    def appendTail(self, value: int) -> None:
        self.stack1.append(value)


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


# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
posted @ 2021-01-08 12:13  WangSJiNa  阅读(43)  评论(0)    收藏  举报