您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)使用Java 1.8數(shù)組實現(xiàn)循環(huán)隊列,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
1、引入
使用數(shù)組實現(xiàn)循環(huán)隊列,功能如下:
1)isFull():隊列滿?
2)isEmpty():隊列空?
3)add():添加元素。
4)pop():移除元素。
5)display():展示隊列。
6)getSize():獲取當(dāng)前隊列元素個數(shù)。
2、代碼
package DataStructure; import java.util.Arrays; /** * @author: Inki * @email: inki.yinji@qq.com * @create: 2020 1022 * @last_modify: 2020 1023 */ public class MyArrayQueue<AnyType> { /** * The default max size of my array queue. */ private final int DEFAULT_MAX_SIZE = 10; /** * The max size of my array queue. */ private int maxSize; /** * The front of my array queue. */ private int front; /** * The rear of my array queue. */ private int rear; /** * Using array to simulate queue. */ private AnyType[] arrQueue; /** * The first constructor. */ public MyArrayQueue() { this(DEFAULT_MAX_SIZE); }//Of the first constructor /** * The second constructor. */ public MyArrayQueue(int paraMaxSize) { maxSize = paraMaxSize + 1; arrQueue = (AnyType[]) new Object[maxSize]; front = 0; rear = 0; }//Of the second constructor /** * Queue is full? * @return: * True if full else false. */ public boolean isFull() { return (rear + 1) % maxSize == front; }//Of isFull /** * Queue is empty? * @return: * True if empty else false. */ public boolean isEmpty() { return front == rear; }//Of isEmpty /** * Add element. * @param: * paraVal: * The given value. */ public void add(AnyType paraVal) { if(isFull()) { System.out.println("The queue is full."); return; }//Of if arrQueue[rear] = paraVal; rear = (rear + 1) % maxSize; }//Of add /** * Pop element. */ public AnyType pop() { if (isEmpty()) { throw new RuntimeException("The queue is full."); }//Of if AnyType retVal = arrQueue[front]; front = (front + 1) % maxSize; return retVal; }//of pop /** * Display array queue. */ public void display() { if (isEmpty()) { System.out.println("The queue is empty."); return; }//Of if System.out.print("The queue is: ["); int i = front; while (i != (rear + maxSize- 1) % maxSize) { System.out.printf("%s, ", arrQueue[i]); i = (i + 1) % maxSize; }//Of while System.out.printf("%s]", arrQueue[rear - 1]); }//Of display /** * Get current size of my array queue. */ public int getSize() { return (rear - front + maxSize) % maxSize + 1; }//Of getSize /** * The main **/ public static void main(String[] args) { MyArrayQueue <Integer> testArrayQueue = new MyArrayQueue<>(3); testArrayQueue.add(1); testArrayQueue.add(2); testArrayQueue.add(4); testArrayQueue.pop(); testArrayQueue.display(); }//Of main }//Of MyArrayQueue
以上就是使用Java 1.8數(shù)組實現(xiàn)循環(huán)隊列,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。