使用java實現隊列數據結構


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;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM