📄 queue.java
字号:
package org.huhuiyu.datastructures;
public class Queue<T> {
private Node<T> head; // 头节点
private Node<T> tail; // 尾节点
private int count;
public Queue() {
clear();
}
/**
* 加入数据到队列
*
* @param data
* 加入到队列的数据
*/
public void enqueue(T data) {
Node<T> add = new Node<T>(data);
if (isEmpty()) {
head = add;
tail = head;
}
else {
// 添加到尾部
tail.setNext(add);
tail = add;
}
count++;
}
/**
* 出队并返回出队的数据
*
* @return 出队的数据
*/
public T dequeue() {
if (isEmpty()) {
throw new IllegalStateException("队列是空的!");
}
// 移除并返回头数据
T data = head.getData();
head = head.getNext();
count--;
if (isEmpty()) {
tail = null; // 置空尾指针
}
return data;
}
/**
* 查看排在队列最前端的数据
*
* @return 排在队列最前端的数据
*/
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("队列是空的!");
}
return head.getData();
}
public void clear() {
head = null;
tail = null;
count = 0;
}
public boolean isEmpty() {
return count == 0;
}
public int size() {
return count;
}
public static void main(String[] args) {
Queue<Integer> queue = new Queue<Integer>();
for (int i = 1; i <= 10; i++) {
queue.enqueue(i);
}
System.out.println("size():" + queue.size());
while (!queue.isEmpty()) {
System.out.println(queue.dequeue());
}
System.out.println("size():" + queue.size());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -