?? 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 + -