刷题--用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

我一开始的想法是每次要出队列的时候,将栈1中的元素全部出栈到栈2,栈顶即是要出队列的元素,然后再将栈2的元素全部出栈回栈1。这样操作时间复杂度略高。
更为简洁的办法是当栈2为空时,栈1全部出栈到栈2,栈2只用来出队列。

# -*- coding:utf-8 -*-
class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return len(self.items) == 0

    def push(self, node):
        self.items.append(node)

    def pop(self):
        if not self.isEmpty():
            return self.items.pop()

class Solution:
    def __init__(self):
        self.stack1 = Stack()
        self.stack2 = Stack()

    def push(self, node):
        # write code here
        self.stack1.push(node)

    def pop(self):
        if self.stack2.isEmpty():
            while not self.stack1.isEmpty():
                self.stack2.push(self.stack1.pop())

        return self.stack2.pop()

猜你喜欢

转载自blog.csdn.net/treasure_z/article/details/79913638