队列

本文介绍了队列作为先进先出(FIFO)数据结构的基本原理和API设计。队列使用单链表实现,提供了enqueue方法用于在尾部插入元素,dequeue方法用于从头部移除元素,并通过isEmpty和size方法检查队列状态。此外,还展示了队列内部节点的定义以及迭代器的实现,以遍历队列中的元素。
摘要由CSDN通过智能技术生成

队列

​ 队列是一种基于先进先出(FIFO)的数据结构,是一种只能在一端进行插入,在另一端进行删除操作的特殊线性表,它按照先进先出的原则存储数据,先进入的数据,在读取数据时先读被读出来。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cR6zhvGU-1626938866419)(E:\personal\Node\数据结构与算法\笔记\assets\image13.png)]

队列的API设计

方法名方法功能
public boolean isEmpty()判断队列是否为空,是返回true,否返回false
public int size()获取队列中元素的个数
public T dequeue()从队列中拿出一个元素
public void enqueue(T t)往队列中插入一个元素

队列的实现

/**
 * 队列--单链表实现
 */
public class Queue<T> implements Iterable<T> {
    // 记录首结点
    private Node head;
    // 记录尾结点
    private Node last;
    // 记录元素个数
    private int N;

    public Queue() {
        head = new Node(null, null);
        last = null;
        N = 0;
    }

    // 判断队列是否为空
    public boolean isEmpty() {
        return N == 0;
    }

    // 返回队列中元素的个数
    public int size() {
        return N;
    }

    // 向队列中插入元素t(尾插法)
    public void enqueue(T t) {
        // 判断队列是否为空
        if (isEmpty()) {
            last = new Node(t, null);
            head.next = last;
        } else {
            // 记录当前的尾结点
            Node oldLast = last;
            // 记录新的尾结点
            last = new Node(t, null);
            // 链接新的尾结点
            oldLast.next = last;
        }
        // 元素个数+1
        N++;
    }

    // 从队列中拿出一个元素
    public T dequeue() {
        // 判断队列是否为空
        if (isEmpty()) {
            return null;
        }
        // 记录当前第一个结点
        Node oldFirst = head.next;
        // 头结点指向新的第一个结点
        head.next = oldFirst.next;
        // 元素个数-1
        N--;
        return oldFirst.item;
    }

	
    private class Node {
        private T item;
        private Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator<T> {
        private Node n;

        public QIterator() {
            n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农村小白i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值