面试题9:用两个栈实现队列

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。

class Solution:
    def __init__(self):
        self.stackA = []
        self.stackB = []
    # 进栈,放入栈A中
    def push(self, node):
        self.stackA.append(node)

    # 出栈
    def pop(self):
        # 1.如果栈B不为空,直接弹出
        if self.stackB:
            return self.stackB.pop()
        # 2.如果栈B为空,栈A也为空,返回None
        elif not self.stackA:
            return None
        # 3.如果栈B为空,栈A不为空
        else:
            while self.stackA:
                self.stackB.append(self.stackA.pop())
            return self.stackB.pop()

题目:用两个队列实现一个栈

class Solution:
    def __init__(self):
        self.queueA = []
        self.queueB = []
    # 插入队列
    def push(self, node):
        self.queueA.insert(0, node)
    def pop(self):
        if not self.queueA:
            return None
        while len(self.queueA)!=1:
            self.queueB.insert(0, self.queueA.pop())
        self.queueA, self.queueB = self.queueB, self.queueA
        return self.queueB.pop()

 测试代码:

if __name__=="__main__":
    solution = Solution()
    solution.push("a")
    solution.push("b")
    solution.push("c")
    print(solution.pop())

 

点赞