返回介绍

Implement Queue by Two Stacks

发布于 2025-02-22 13:01:34 字数 1924 浏览 0 评论 0 收藏 0

Source

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element), 
pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Example
For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2

Challenge
implement it by two stacks, do not use any other data structure and push, 
pop and top should be O(1) by AVERAGE.

题解

两个栈模拟队列,栈是 LIFO, 队列是 FIFO, 故用两个栈模拟队列时可结合栈 1 和栈 2, LIFO + LIFO ==> FIFO, 即先将一个栈元素全部 push 到另一个栈,效果即等价于 Queue.

Java

public class Solution {
  private Stack<Integer> stack1;
  private Stack<Integer> stack2;

  public Solution() {
    // source stack
    stack1 = new Stack<Integer>();
    // target stack
    stack2 = new Stack<Integer>();
  }

  public void push(int element) {
    stack1.push(element);
  }

  public int pop() {
    if (stack2.empty()) {
      stack1ToStack2(stack1, stack2);
    }
    return stack2.pop();
  }

  public int top() {
    if (stack2.empty()) {
      stack1ToStack2(stack1, stack2);
    }
    return stack2.peek();
  }

  private void stack1ToStack2(Stack<Integer> stack1, Stack<Integer> stack2) {
    while (!stack1.empty()) {
      stack2.push(stack1.pop());
    }
  }
}

源码分析

将栈 1 作为原始栈,将栈 1 元素压入栈 2 是公共方法,故写成一个私有方法。

复杂度分析

视连续 push 的元素而定,时间复杂度近似为 O(1)O(1)O(1).

Reference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文