栈和队列基础

先进后出

队列

先进先出

卡哥栈和队列基础

用栈实现队列

java 中有stack 和Deque 两种类型可以实现栈

java 复制代码
class MyQueue {
    Deque<Integer> stack1;
    Deque<Integer> stack2;
    public MyQueue() {
        stack1=new ArrayDeque<Integer>();
        stack2=new ArrayDeque<Integer>();
    }
    
    public void push(int x) {
        stack1.addFirst(x);
    }
    
    public int pop() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
            int s =stack1.removeFirst();
            stack2.addFirst(s);
            }
        }
        return stack2.removeFirst();
    }
    
    public int peek() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
            int s =stack1.removeFirst();
            stack2.addFirst(s);
            }
        }
        int ss= stack2.removeFirst();
        stack2.addFirst(ss);
        return ss;
    }
    
    public boolean empty() {
        return stack2.isEmpty()&&stack1.isEmpty();
    }
}

/**
 * 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();
 */

用队列实现栈

队列有两种类型Deque Queue

java 复制代码
class MyStack {
    Deque<Integer> deque1;
    Deque<Integer> deque2;
    public MyStack() {
        deque1=new ArrayDeque<Integer>();
        deque2=new ArrayDeque<Integer>();
    }
    
    public void push(int x) {
        deque2.offer(x); // 先放在辅助队列中
        while (!deque1.isEmpty()){
            deque2.offer(deque1.poll());
        }
        Deque<Integer> queueTemp;
        queueTemp = deque2;
        deque2 = deque1;
        deque1 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
    }
    
    public int pop() {
        return deque1.poll();
    }
    
    public int top() {
        return deque1.peek();
    }
    
    public boolean empty() {
        return deque1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
相关推荐
gadiaola5 分钟前
【JVM】Java虚拟机(二)——垃圾回收
java·jvm
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan3 小时前
c++ 单例模式
开发语言·c++·单例模式
coderSong25683 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy4 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之4 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头4 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#