栈和队列基础

先进后出

队列

先进先出

卡哥栈和队列基础

用栈实现队列

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();
 */
相关推荐
冷雨夜中漫步3 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
JH30734 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
m0_736919105 小时前
C++代码风格检查工具
开发语言·c++·算法
Coder_Boy_5 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
2501_944934735 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
invicinble5 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟5 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖5 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472466 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ7 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto