栈和队列的实现

用栈实现队列

1.分析

2.代码

java 复制代码
class MyQueue {
      private Stack<Integer> s1;
      private Stack<Integer> s2;
    public MyQueue() {
      s1 = new Stack<>();
      s2 = new Stack<>();
    }
    
    public void push(int x) {
        s1.push(x);
    }
    
    public int pop() {
        if(empty()){
            return -1;
        }
        if(s2.empty()){
            while(!s1.empty()){
                s2.push(s1.pop());
            }
        }
       return s2.pop();
    }
    
    public int peek() {
         if(empty()){
            return -1;
        }
        if(s2.empty()){
            while(!s1.empty()){
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }
    
    public boolean empty() {
     return s1.empty()&&s2.empty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
相关推荐
阿正的梦工坊1 小时前
JavaScript 微任务与宏任务完全指南
开发语言·javascript·ecmascript
励志的小陈1 小时前
数据结构--二叉树知识讲解
数据结构
chools1 小时前
【AI超级智能体】快速搞懂工具调用Tool Calling 和 MCP协议
java·人工智能·学习·ai
知行合一。。。2 小时前
Python--05--面向对象(属性,方法)
android·开发语言·python
李白你好2 小时前
TongWeb EJB 反序列化生成工具(Java-Chain 插件)
java·安全
青梅橘子皮2 小时前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
笨笨饿2 小时前
#58_万能函数的构造方法:ReLU函数
数据结构·人工智能·stm32·单片机·硬件工程·学习方法
浅时光_c2 小时前
3 shell脚本编程
linux·开发语言·bash
Evand J2 小时前
【三维轨迹目标定位,CKF+RTS,MATLAB程序】基于CKF与RTS平滑的三维非线性目标跟踪(距离+方位角+俯仰角)
开发语言·matlab·目标跟踪
U盘失踪了3 小时前
Java 的 JAR 是什么?
java·jar