Microsoft 面试题 #3 — Implement Queue using Stacks|用栈实现队列

53次阅读
没有评论

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)
用两个栈:inout

  • 入队:直接 in.push(x)
  • 出队 / 取队首:若 out 为空,把 in 中所有元素逐个弹出并压入 out,再从 out.pop()
  • 判空:inout 同时为空。
    摊还时间复杂度 O(1),最坏单次 O(n)。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括微软、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0