返回轨道
算法 · 2026-05-14 · 14 阅读

P122 使用栈实现队列

算法 14 阅读

信号摘要

难度:Easy · 时长:03:59 · leetcode 232 · lintcode 40

P122 使用栈实现队列

未对外公开播放权限
点击查看说明

描述

这个题目说的是,你要使用栈来实现一个队列,需要实现队列中常用的 4 个函数。其中,push 函数往队尾加入一个元素;pop 函数把队首元素移除;peek 函数返回队首元素;empty 函数返回队列是否为空。另外你的实现不需要考虑异常操作情况,比如从一个空队列里 pop 元素。

代码

public class AlgoCasts {

  public class MyQueue {

    private Stack<Integer> in = new Stack<>(), out = new Stack<>();

    private void transferIfEmpty() {
      if (out.empty())
        while (!in.empty())
          out.push(in.pop());
    }

    public void push(int x) {
      in.push(x);
    }

    public int pop() {
      transferIfEmpty();
      return out.pop();
    }

    public int peek() {
      transferIfEmpty();
      return out.peek();
    }

    public boolean empty() {
      return in.empty() && out.empty();
    }
  }

}

📡 通讯频道