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

基础数据结构——队列(链表实现)

队列的性质

  • 先进先出(FIFO - First In First Out):最先加入队列的元素最先被移出
  • 后进后出(后来的元素排在队尾)
  • 只允许在队尾插入元素,在队首删除元素
  • 具有先来先服务的特点

链表实现队列

和之前创建链表相同,我们需要设置一个哨兵头结点 此时它既是head也是tail

后面进行添加操作的之后将每次新加的节点设置为tail,并且指向head

我们接下来实现队列的基本操作

先来写队列类和它内部Node类

public class LinkedListQueue <E>implements Queue<E>, Iterable<E>{
    Node<E> head=new Node<>(null,null);//头指针一直指向哨兵节点
    Node<E> tail=head;
    int size=0;
    int capacity=Integer.MAX_VALUE;
    {
        tail.next=head;
    }

    private static class Node<E>{
        E value;
        Node<E> next;

      public Node(E value, Node<E> next) {
          this.value = value;
          this.next = next;
    }
}

    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    public LinkedListQueue() {

}

我们在这个类中将每次构造的队列对象的tail节点都指向head节点

接下来我们实现各个功能操作

代码如下

public boolean offer(E value) {
        if(isFull()){
            return false;
        }
        Node<E> added=new Node<>(value,head);
        tail.next=added;
        tail=added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        Node<E> first=head.next;
        head.next=first.next;
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if(isEmpty()){
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return head==tail;
    }

    @Override
    public boolean isFull() {
        return size==capacity;
    }
}


http://www.kler.cn/a/383944.html

相关文章:

  • 【django】Django REST Framework (DRF) 项目中实现 JWT
  • Caused by: org.apache.flink.api.common.io.ParseException: Row too short:
  • Java实现pdf转图片
  • ipv6的 fc00(FC00::/7) 和 fec0(FEC0::/10)
  • 深度学习:Masked Self-Attention 详解
  • 【Chapter 2_ Sentosa_DSML Community Edition Product Features】
  • 职场浅谈:情商高的“4”种表现,情商高的人才更容易走向成功
  • yolo v5 开源项目
  • 基于Spring Boot的中小型制造企业质量管理系统设计与实现,LW+源码+讲解
  • Cesium 贝塞尔曲线
  • 【Ai测评】GPT Search偷偷上线,向Google和微软发起挑战!
  • win11安装最新rabbitmq
  • SSM— spring,springMVC,mybatis整合
  • Flutter鸿蒙next 实现一个计算器应用
  • SpringBoot中使用SpringTask实现定时任务
  • OpenDroneMap Webodm
  • java-web-苍穹外卖-day1:软件开发步骤简化版+后端环境搭建
  • OCR、语音识别与信息抽取:免费开源的AI平台在医疗领域的创新应用
  • Rust智能指针和生命周期
  • 栈虚拟机和寄存器虚拟机,有什么不同?