两个栈实现队列(D)

java 复制代码
import java.util.Stack;

public class TwoStackQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    public TwoStackQueue() {
        stackPush = new Stack<Integer>();
        stackPop = new Stack<Integer>();
    }

    private void pushToPop() {
        if (stackPop.empty()) {
            while (!stackPush.empty()) {
                stackPop.push(stackPush.pop());
            }
        }
    }

    public void add(int pushInt) {
        stackPush.push(pushInt);
        pushToPop();
    }

    public int poll() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        pushToPop();
        return stackPop.pop();
    }

    public int peek() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        pushToPop();
        return stackPop.peek();
    }

    public static void main(String[] args) {
        TwoStackQueue queue = new TwoStackQueue();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.poll());

    }
}

这个算法通过两个栈结构巧妙地模拟了一个队列的行为,其中stackPush用于处理入队操作,而stackPop用于处理出队操作。当需要出队时,算法会检查stackPop是否为空,如果为空,则将stackPush中的所有元素逆序转移到stackPop中,从而确保stackPop的栈顶元素是队列的头部元素。这种方法使得入队操作的时间复杂度为O(1),而出队操作在最坏情况下的时间复杂度为O(n),但平均时间复杂度仍为O(1),因为每个元素只被移动一次。整体上,该算法高效地利用了栈的后入先出特性来实现了队列的先进先出特性。

相关推荐
aiee1 分钟前
GO通过SMTP协议发送邮件
开发语言·后端·golang
云浩舟12 分钟前
Golang并发读取json文件数据并写入oracle数据库的项目实践
开发语言·数据库·golang
廖显东-ShirDon 讲编程17 分钟前
《零基础Go语言算法实战》【题目 2-22】Go 调度器优先调度问题
算法·程序员·go语言·web编程·go web
walkskyer18 分钟前
Golang strconv包详解:高效类型转换实战
android·开发语言·golang
我命由我1234522 分钟前
Android Room 构建问题:There are multiple good constructors
android·开发语言·java-ee·android studio·android jetpack·android-studio·android runtime
Lulsj40 分钟前
代码随想录day24 | 贪心算法理论基础 leetcode 455.分发饼干 376.摆动序列 53. 最大子序和
算法·leetcode·贪心算法
KuaCpp41 分钟前
算法初学者(图的存储)链式前向星
c++·算法
JINGWHALE143 分钟前
设计模式 行为型 备忘录模式(Memento Pattern)与 常见技术框架应用 解析
前端·人工智能·后端·设计模式·性能优化·系统架构·备忘录模式
Cosmoshhhyyy1 小时前
LeetCode:2270. 分割数组的方案数(遍历 Java)
java·算法·leetcode
zhulangfly1 小时前
【Java设计模式-4】策略模式,消灭if/else迷宫的利器
java·设计模式·策略模式