两个栈实现一个队列

2022-09-07 11:30:37 浏览数 (1)

代码语言:javascript复制
class Solution(object):
    """
    两个栈实现一个队列
    """
    def __init__(self):
        # -----
        self.stack1 = []
        self.stack2 = []

    def push(self, element):
        self.stack1.append(element)

    def pop(self):
        if self.stack2 == [] and self.stack1 == []:
            raise IndexError("index out of range, stack is empty now!")

        for val in range(len(self.stack1)):
            self.stack2.append(self.stack1.pop(0))
        return self.stack2.pop(0)

life is a boat

0 人点赞