当前位置: 首页 > article >正文

Java之队列

1. 概念

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性
特点队列具有先进先出FIFO(First In First Out)
入队列:进行插入操作的一端称为队尾(Tail/Rear)
出队列:进行删除操作的一端称为队头(Head/Front)
在这里插入图片描述

2. 队列的使用

在Java中,Queue是个接口,底层是通过链表实现的。

注意:Queue是个接口,在实例化时必须实例化LinkedList的对象,因为LinkedList实现了Queue接口。
比如:Queue<Integer> q = new LinkedList<>();

在这里插入图片描述
Java中队列提供的一些使用方法如下:

方法功能
boolean offer(E e)入队列
E poll()出队列
peek()获取队头元素
int size()获取队列中有效元素个数
boolean isEmpty()检测队列是否为空

3. 模拟实现队列

我们可以使用双向链表来模拟实现队列

1. 首先创建一个内部类 ,定义节点,并采用构造方法初始化

static class QueNode{
public QueNode prev;
public QueNode next;
int val;
public QueNode(int val) {
this.val = val;
}
}

2. 定义两个引用分别指向队头和队尾

public QueNode front;
public QueNode rear;

3. 相关方法的实现

public class MyQueue {

    static class QueNode{
        public QueNode prev;
        public QueNode next;
        int val;
        public QueNode(int val) {
            this.val = val;
        }
    }

    public QueNode front;
    public QueNode rear;


    //入队尾


    public void offer(int data){
        QueNode queNode=new QueNode(data);
        if(front==null){
            front=rear=queNode;
        }else {
            rear.next=queNode;
            queNode.prev=rear;
            rear=queNode;
        }
    }

    //队头出数据
  
    public void poll(){
        int data=0;
        if(front==null){
        }else {
            data=front.val;
            front=front.next;
            front.prev=null;
            if(front==null){
                rear=null;
            }
        }
        return data;
    }

    // 求队长

    public int size(){
        if(front==null){
            return 0;
        }
        QueNode cur=front;
        int size=0;
        while (cur!=null){
            size++;
            cur=cur.next;
        }
        return size;
    }

    //取队头元素

    public int peek(){
        if(front==null){
            return -1;
        }
        return front.val;
    }
    //队列的打印
    public void display(){
        if(front==null){
            return ;
        }
        QueNode cur=front;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur=cur.next;
        }
        System.out.println();
    }
}

http://www.kler.cn/news/333594.html

相关文章:

  • Pikachu-url重定向-不安全的url跳转
  • Redis基础三(redis的高级配置)
  • 【rCore OS 开源操作系统】Rust 字符串(可变字符串String与字符串切片str)
  • C++:STL常用算法随笔
  • Prometheus之Pushgateway使用
  • 静态路由故障排查
  • python中的copy方法
  • 为什么MySQL不建议使用delete删除数据
  • 基于springboot vue 电影推荐系统
  • 掌握 C# 多线程与异步编程
  • 408笔记|随笔记录|自用|2
  • (Linux驱动学习 - 6).Linux中断
  • JDK——java.util.function
  • [Python学习日记-39] 闭包是个什么东西?
  • 【2023工业3D异常检测文献】PointCore: 基于局部-全局特征的高效无监督点云异常检测器
  • javascript-obfuscator js混肴 (用户界面版)
  • 【ECMAScript 从入门到进阶教程】第四部分:项目实践(项目结构与管理,单元测试,最佳实践与开发规范,附录)
  • [SQL] SQL语句注意事项
  • Python——异常处理机制
  • AJAX 1——axios体验、认识URL、常用请求方法、HTTP协议、错误处理、form-serialize插件