public class Queue {
// 单链表实现队列
public static class Node<V> {
public V value;
public Node<V> next;
public Node(V v) {
value = v;
}
}
public static class Queue<V> {
private Node<V> head;
private Node<V> tail;
private int size;
public Queue() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void offer(V value) {
Node<V> currentNode = new Node<>(value);
if (tail == null) {
head = currentNode;
} else {
tail.next = currentNode;
}
tail = currentNode;
size++;
}
public V poll() {
V ans = null;
if (head != null) {
ans = head.value;
head = head.next;
size--;
} else {
tail = null;
}
return ans;
}
public V peek() {
V ans = null;
if (head != null) {
ans = head.value;
}
return ans;
}
}
public static void main(String[] args) {
Queue<Integer> queue = new Queue<>();
for (int i = 0; i < 10; i++) {
queue.offer(i);
}
while (!queue.isEmpty()) {
System.out.print(queue.poll() + " ");
}
}
}
单链表实现队列
最新推荐文章于 2024-10-10 09:56:47 发布
该代码示例展示了如何使用Java创建一个基于单链表的队列数据结构。队列具有offer()方法用于添加元素,poll()方法用于移除并返回队首元素,以及peek()方法查看队首元素但不移除。在main方法中,创建了一个队列并填充了数字,然后逐个打印出队列中的元素。
摘要由CSDN通过智能技术生成