数据结构——LinkedQueue的实现

本文探讨了队列作为先进先出的数据结构,重点解析了使用链表实现的LinkedQueue。通过这种方式,LinkedQueue提供了一种高效管理元素的手段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列是一种先进先出(FIFO)的数据结构,LinkedQueue是用链表实现的,另外还可以用回环数组的方式实现。

LinkedQueue

import java.util.NoSuchElementException;

/**
 * 用单链表的形式实现链式队列
 * 该实现包含有一个指向尾部节点的引用,方便入队列操作的实现
 * @author Bingo
 *
 * @param <T>
 */
public class LinkedQueue<T> {
    private int size;
    private Node<T> head;
    private Node<T> tail;

    public LinkedQueue(){
        size = 0;
        tail = head = new Node<T>(null, null);
    }

    public int size(){
        return size;
    }

    public boolean isEmpty(){
        return size() == 0;
        //return head == tail;
    }

    /**
     * 进队列,在链表的尾部添加新的元素
     * @param ele
     */
    public void enqueue(T ele){
        Node<T> newNode = new Node<T>(ele, null);
        tail.next = newNode;
        tail = newNode;
        size++;
    }

    /**
     * 出队列,在链表的头部取出元素
     * @return
     */
    public T dequeue(){
        if(isEmpty())
            throw new NoSuchElementException("queue is empty.");

        T oldElement = head.next.element;
        head.next = head.next.next;
        size--;
        return oldElement;
    }

    /**
     * 私有节点类,保存节点元素值和指向下一个节点的引用
     * @author Bingo
     *
     * @param <T>
     */
    private static class Node<T>{
        public T element;
        public Node<T> next;

        public Node(T element, Node<T> next){
            this.element  = element;
            this.next = next;
        }
    }

    @Override
    public String toString() {
        return "size = " + size();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值