java用单链表实现队列
时间: 2024-10-18 21:22:35 浏览: 28
在 Java 中,可以使用单链表实现队列的数据结构,通常使用头插法(enqueue)和尾出法(dequeue)操作。以下是简单的单链表队列实现:
```java
public class LinkedListQueue {
private Node head; // 队首节点
private Node tail; // 队尾节点
// 定义链表节点
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// 入队(enqueue)
public void enqueue(int value) {
if (head == null) {
head = new Node(value);
tail = head;
} else {
Node newNode = new Node(value);
tail.next = newNode;
tail = newNode;
}
}
// 出队(dequeue)
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int removedValue = head.data;
head = head.next;
if (head == null) {
tail = null;
}
return removedValue;
}
// 检查队列是否为空
public boolean isEmpty() {
return head == null;
}
// 返回队列长度
public int size() {
int count = 0;
Node current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
}
阅读全文