下面是使用 LinkedList 实现队列的代码示例。LinkedList 实现了 Queue 接口,因此可以直接作为队列使用,遵循先进先出(FIFO)的原则。
import java.util.LinkedList;
import java.util.Queue;
public class LinkedListQueueDemo {
public static void main(String[] args) {
// 创建一个基于LinkedList的队列
Queue<String> queue = new LinkedList<>();
// 1. 向队列添加元素(入队操作)
// add():添加失败会抛出异常
queue.add("元素A");
// offer():添加失败返回false(更推荐使用)
boolean isAdded = queue.offer("元素B");
System.out.println("元素B是否添加成功:" + isAdded);
queue.offer("元素C");
queue.offer("元素D");
System.out.println("当前队列元素:" + queue);
// 2. 查看队头元素(不删除)
// peek():队列为空时返回null
String head = queue.peek();
System.out.println("队头元素:" + head);
// element():队列为空时抛出异常
String firstElement = queue.element();
System.out.println("队头元素(element()):" + firstElement);
// 3. 移除并返回队头元素(出队操作)
// poll():队列为空时返回null(更推荐使用)
String polled = queue.poll();
System.out.println("出队元素(poll()):" + polled);
// remove():队列为空时抛出异常
String removed = queue.remove();
System.out.println("出队元素(remove()):" + removed);
System.out.println("出队两次后,当前队列:" + queue);
// 4. 遍历队列并清空
System.out.println("依次出队剩余元素:");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
// 验证队列是否为空
System.out.println("队列是否为空:" + queue.isEmpty());
}
}
new LinkedList<>() 创建队列实例,并赋值给 Queue 接口引用,面向接口编程更灵活。add(E e):添加元素到队尾,失败时抛出 IllegalStateException(如队列有容量限制且已满)。offer(E e):添加元素到队尾,失败时返回 false,推荐优先使用。peek():返回队头元素,队列为空时返回 null。element():返回队头元素,队列为空时抛出 NoSuchElementException。poll():移除并返回队头元素,队列为空时返回 null,推荐优先使用。remove():移除并返回队头元素,队列为空时抛出 NoSuchElementException。isEmpty():判断队列是否为空。size():返回队列中元素的数量。运行上述代码,输出结果会展示队列从入队、查看、出队到清空的完整过程,清晰体现FIFO特性。LinkedList 实现的队列适合单线程环境,操作简单但性能略低于 ArrayDeque。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。