Java實(shí)現(xiàn)隊(duì)列的三種方法集合
數(shù)組實(shí)現(xiàn)隊(duì)列
//數(shù)組實(shí)現(xiàn)隊(duì)列class queue{ int[] a = new int[5]; int i = 0; //入隊(duì)操作 public void in(int m) { a[i++] = m; }// 出隊(duì)列操作 取出最前面的值 通過循環(huán)遍歷把所有的數(shù)據(jù)向前一位 public int out() { int index = 0; int temp = a[0]; for(int j = 0;j < i;j++) { a[j] = a[j + 1]; } return temp; } }
ArrayList實(shí)現(xiàn)隊(duì)列
//集合實(shí)現(xiàn)隊(duì)列class queue{ List<Integer> list = new ArrayList<Integer>(); int index = 0; public void in(int n) { list.add(n); index++; } //出隊(duì)列操作 //出隊(duì) public int out(){ if(!list.isEmpty()){ index--; return list.remove(0); } return -1; } }
兩個堆棧實(shí)現(xiàn)隊(duì)列
//兩個堆棧實(shí)現(xiàn)一個隊(duì)列class queue3 { Stack<Integer> stackA = new Stack<Integer>(); Stack<Integer> stackB = new Stack<Integer>(); //入隊(duì) public void in(int n) { stackA.push(n); } //出隊(duì) 我們把A里面的元素遍歷拿出放入B中 再拿出B中的第一個元素 public int out() { //判斷b棧有沒有元素 有返回false 無返回真 if(stackB.isEmpty()) { while(!stackA.isEmpty()) { stackB.push(stackA.pop()); } } return stackB.pop(); }}
補(bǔ)充知識:java使用鏈表實(shí)現(xiàn)隊(duì)列
隊(duì)列使用Java進(jìn)行鏈表實(shí)現(xiàn),在網(wǎng)上找到了一張圖,很好,借鑒一下

設(shè)置兩個結(jié)點(diǎn)node,front指向隊(duì)首元素,rear指向隊(duì)尾;
上代碼:
public class LinkedQueue { Node front;//隊(duì)頭指針,指向隊(duì)頭節(jié)點(diǎn) Node rail;//隊(duì)尾指針,指向隊(duì)尾節(jié)點(diǎn) int size = 0;//記錄隊(duì)列長度 //構(gòu)造函數(shù) public LinkedQueue() { front = rail = null; } public boolean isEmpty() { return size == 0 ? true : false; } //添加元素 public boolean addQueue(Object ele) { if (size == 0) { front = new Node(null, ele); rail = front; size++; return true; } Node s = new Node(null, ele); //這塊有個主意的地方,一旦rail設(shè)置了next屬性,因?yàn)閒ront節(jié)點(diǎn)與rail節(jié)點(diǎn)指向了同一個node節(jié)點(diǎn),持有同一個結(jié)點(diǎn)的一個引用,因此front節(jié)點(diǎn)next屬性也被填充 rail.setNext(s); rail = s; size++; return true; } /** * 刪除元素,出隊(duì)列 * @return */ public boolean deleteQueue() { if (isEmpty()) { System.out.println('當(dāng)前隊(duì)列為空'); return false; } front = front.next; size--; return true; } public static void main(String[] args) { LinkedQueue queue = new LinkedQueue(); queue.addQueue(1); queue.addQueue(2); queue.addQueue(3); queue.deleteQueue(); } } /** * 首先鏈表底層是一個個結(jié)點(diǎn) */class Node { Node next; Object element; public Node(Node next, Object element) { this.next = next; this.element = element; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public Object getElement() { return element; } public void setElement(Object element) { this.element = element; } }
以上這篇Java實(shí)現(xiàn)隊(duì)列的三種方法集合就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP新手必備的基礎(chǔ)知識2. asp文件用什么軟件編輯3. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )4. js實(shí)現(xiàn)計(jì)算器功能5. golang中json小談之字符串轉(zhuǎn)浮點(diǎn)數(shù)的操作6. 通過IEAD+Maven快速搭建SSM項(xiàng)目的過程(Spring + Spring MVC + Mybatis)7. 利用CSS制作3D動畫8. IDEA 2020.1.2 安裝教程附破解教程詳解9. Vue axios獲取token臨時令牌封裝案例10. JS中6個對象數(shù)組去重的方法

網(wǎng)公網(wǎng)安備