Java通过链表实现队列
生活随笔
收集整理的這篇文章主要介紹了
Java通过链表实现队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
class LinkedQueue<T> {/*** 隊列大小,由構造函數(shù)初始化*/private int maxSize;/*** 隊頭*/private Node front = null;/*** 隊尾*/private Node rear = null;/*** 隊列實際元素個數(shù)*/private int nItems;/*** 初始化隊列,并指定隊列長度* * @param maxSize*/public LinkedQueue(int maxSize) {this.maxSize = maxSize;front = null;rear = null;this.nItems = 0;}/*** 講一個數(shù)據(jù)放入隊列* * @param data*/public void enqueue(T data) {Node node = new Node(data);if (isEmpty()) {front = node;front.next = null;rear = node;rear.pre = null;nItems++;return;}if (size() == 1) {rear = node;front.next = rear;rear.pre = front;nItems++;return;}if (isFull()) {System.out.print("超過隊列已滿,無法入隊");return;}node.pre = rear;rear.next = node;rear = node;nItems++;}/*** 將數(shù)據(jù)出隊* * @return*/public T dequeue() {Node temp = null;if (isEmpty()) {System.out.println("隊列已空,無法出隊");return null;}if (size() == 1) {temp = front;front = null;rear = null;nItems--;return temp.data;}if (size() == 2) {temp = front;front = rear;front.next = null;rear.pre = null;nItems--;return temp.data;}temp = front;front = front.next;nItems--;return temp.data;}/*** 判斷隊列是否為空* * @return*/public boolean isEmpty() {return nItems == 0;}/*** 判斷隊列是否已滿* * @return*/public boolean isFull() {return nItems == maxSize;}/*** 獲取隊列的實際數(shù)據(jù)個數(shù)* * @return*/public int size() {return nItems;}/*** 將數(shù)據(jù)封裝成節(jié)點* * @author John**/private class Node {T data;Node next;Node pre;public Node(T data) {this.data = data;}}
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/SaraMoring/p/5794383.html
總結
以上是生活随笔為你收集整理的Java通过链表实现队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用yum时,保留下载包设置
- 下一篇: C++基础知识之vector