Node節點元素:
public class Node<T> {
private T data;
private Node next;
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return this.next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(T data) {
this.data = data;
}
}
隊列實現:
public class LinkQueue<T> {
private Node<T> front; //隊列頭部
private Node<T> rear; //隊列尾部
private int size; //隊列長度
//指定隊列的構造方法,並且做節點的初始化
public LinkQueue() {
front = rear = null;
}
//入隊
public void putQueue(T t) {
//創建隊列的一個節點
Node<T> tNode = new Node<>(t);
if(isEmpty()) {
front = rear = tNode;
}else {
this.rear.setNext(tNode);
this.rear = tNode; //始終指定隊尾的元素
}
size ++; //記錄插入Node個數
}
//出隊
public T popQueue() throws Exception {
//判斷隊列是否為空
if(isEmpty()) {
throw new Exception("the queue is empty");
}
Node<T> popData = this.front; //備份當前node對象
this.front = front.getNext();
popData.setNext(null); //設置隊列頭節的下一個節點為null,等着GC回收
size --;
if(size == 0) {
rear = front = null;
}
return popData.getData();
}
//獲取對頭值
public T getFrontData() {
return this.front.getData();
}
//獲取隊尾值
public T getRearData() {
return this.rear.getData();
}
//判斷隊列是否為空
public boolean isEmpty() {
return (front == null && rear == null) ? true: false;
}
}