在TestQueue类里面创建一个链队列,将数字0-9按顺序入队列,并对其进行遍历,输出遍历结果。
时间: 2024-04-29 18:23:30 浏览: 57
代码如下:
```java
public class TestQueue {
public static void main(String[] args) {
LinkedQueue<Integer> queue = new LinkedQueue<>();
for (int i = 0; i < 10; i++) {
queue.enqueue(i);
}
System.out.print("遍历结果:");
while (!queue.isEmpty()) {
System.out.print(queue.dequeue() + " ");
}
}
}
```
其中,`LinkedQueue`是链队列的实现类,代码如下:
```java
public class LinkedQueue<T> {
private Node<T> front; // 队头指针
private Node<T> rear; // 队尾指针
private static class Node<T> {
T data; // 数据域
Node<T> next; // 指针域
public Node(T data) {
this.data = data;
}
}
public LinkedQueue() {
front = rear = null;
}
// 入队
public void enqueue(T data) {
Node<T> node = new Node<>(data);
if (isEmpty()) {
front = rear = node;
} else {
rear.next = node;
rear = node;
}
}
// 出队
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty!");
}
T data = front.data;
front = front.next;
if (front == null) {
rear = null;
}
return data;
}
// 队列是否为空
public boolean isEmpty() {
return front == null;
}
}
```
运行结果:
```
遍历结果:0 1 2 3 4 5 6 7 8 9
```
阅读全文