温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在 Java 中实现自定义 Queue

发布时间:2025-01-23 14:44:37 阅读:95 作者:小樊 栏目:编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,您可以使用LinkedList类来实现自定义队列

import java.util.LinkedList;

public class CustomQueue<T> {
    private LinkedList<T> list = new LinkedList<T>();

    // 入队操作
    public void enqueue(T item) {
        list.addLast(item);
    }

    // 出队操作
    public T dequeue() {
        if (isEmpty()) {
            throw new IllegalStateException("队列为空");
        }
        return list.removeFirst();
    }

    // 查看队首元素
    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("队列为空");
        }
        return list.getFirst();
    }

    // 判断队列是否为空
    public boolean isEmpty() {
        return list.isEmpty();
    }

    // 获取队列大小
    public int size() {
        return list.size();
    }
}

这个CustomQueue类是一个泛型类,可以存储任何类型的对象。它使用LinkedList作为内部数据结构,实现了基本的队列操作,如入队、出队、查看队首元素、判断队列是否为空和获取队列大小。

要使用这个自定义队列,您可以像下面这样实例化一个对象并执行操作:

public static void main(String[] args) {
    CustomQueue<Integer> queue = new CustomQueue<>();

    queue.enqueue(1);
    queue.enqueue(2);
    queue.enqueue(3);

    System.out.println("队首元素: " + queue.peek()); // 输出: 队首元素: 1
    System.out.println("出队操作: " + queue.dequeue()); // 输出: 出队操作: 1
    System.out.println("队首元素: " + queue.peek()); // 输出: 队首元素: 2
    System.out.println("队列大小: " + queue.size()); // 输出: 队列大小: 2
}

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×