← 中文资源

简体中文版本

两个栈拼出均摊 O(1) 的队列

入队压 inbox 栈,outbox 为空时把 inbox 一次性倒入再弹出:每个元素最多搬两次,n 次操作总代价 O(n)、均摊 O(1),FIFO 顺序不乱。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

pop order: a b
pop order: c d
remaining: 0

实现说明

逻辑集中在类 TwoStackQueue和函数 __init__、push、pop、__len__里。 循环只出现在 while self.inbox,它的每次迭代处理一个元素。

使用要点

  • 每一步打印都带着自己的标签:pop order:、remaining:。
  • 调用方只需要 push——其余都是内部实现。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 __init__、push、pop。

主签名形如 def push(self, value)

核心语句

def push(self, value):
    self.inbox.append(value)
def __init__(self):
    self.inbox = []
    self.outbox = []
def __len__(self):
    return len(self.inbox) + len(self.outbox)

代码示例

# Queue from two stacks: push onto the inbox; when the outbox is
# empty, pour the whole inbox over once, then pop from the outbox.
# Each element moves at most twice, so n operations cost O(n) total —
# amortized O(1) per operation — and FIFO order is preserved.
class TwoStackQueue:
    def __init__(self):
        self.inbox = []
        self.outbox = []

    def push(self, value):
        self.inbox.append(value)

    def pop(self):
        if not self.outbox:
            while self.inbox:
                self.outbox.append(self.inbox.pop())
        return self.outbox.pop()

    def __len__(self):
        return len(self.inbox) + len(self.outbox)


queue = TwoStackQueue()
for item in ('a', 'b', 'c'):
    queue.push(item)

print('pop order:', queue.pop(), queue.pop())
queue.push('d')
print('pop order:', queue.pop(), queue.pop())
print('remaining:', len(queue))