Problem statement
Imagine you’re working on a language which only supports Stack, but you need a Queue functionality to fulfill the requirement. Design a queue that supports standard operations using stacks.
要求:在只有“栈”这种原生数据结构的环境里,实现一个“队列”,支持标准队列操作(enqueue, dequeue, peek/front, empty)。
简要思路(CN)
用两个栈:in 和 out。
- 入队:直接
in.push(x); - 出队 / 取队首:若
out为空,把in中所有元素逐个弹出并压入out,再从out.pop(); - 判空:
in与out同时为空。
摊还时间复杂度 O(1),最坏单次 O(n)。
VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括微软、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。