在TestQueue类里面创建一个链队列,将数字0-9按顺序入队列,并对其进行遍历,输出遍历结果
时间: 2024-04-29 19:23:40 浏览: 85
下面是实现代码:
```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);
}
while (!queue.isEmpty()) {
System.out.print(queue.dequeue() + " ");
}
}
}
class LinkedQueue<T> {
private Node<T> head;
private Node<T> tail;
private int size;
public LinkedQueue() {
head = null;
tail = null;
size = 0;
}
public void enqueue(T item) {
Node<T> newNode = new Node<>(item);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
size++;
}
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Queue underflow");
}
T item = head.item;
head = head.next;
size--;
if (isEmpty()) {
tail = null; // to avoid loitering
}
return item;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return size;
}
private static class Node<T> {
private T item;
private Node<T> next;
public Node(T item) {
this.item = item;
next = null;
}
}
}
```
输出结果为:
```
0 1 2 3 4 5 6 7 8 9
```
阅读全文