您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。