Java實現佇列的三種方法集合
阿新 • • 發佈:2020-09-17
陣列實現佇列
//陣列實現佇列 class queue{ int[] a = new int[5]; int i = 0; //入隊操作 public void in(int m) { a[i++] = m; } // 出佇列操作 取出最前面的值 通過迴圈遍歷把所有的資料向前一位 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實現佇列
//集合實現佇列 class queue{ List<Integer> list = new ArrayList<Integer>(); int index = 0; public void in(int n) { list.add(n); index++; } //出佇列操作 //出隊 public int out(){ if(!list.isEmpty()){ index--; return list.remove(0); } return -1; } }
兩個堆疊實現佇列
//兩個堆疊實現一個佇列 class queue3 { Stack<Integer> stackA = new Stack<Integer>(); Stack<Integer> stackB = new Stack<Integer>(); //入隊 public void in(int n) { stackA.push(n); } //出隊 我們把A裡面的元素遍歷拿出放入B中 再拿出B中的第一個元素 public int out() { //判斷b棧有沒有元素 有返回false 無返回真 if(stackB.isEmpty()) { while(!stackA.isEmpty()) { stackB.push(stackA.pop()); } } return stackB.pop(); } }
補充知識:java使用連結串列實現佇列
佇列使用Java進行連結串列實現,在網上找到了一張圖,很好,借鑑一下
設定兩個結點node,front指向隊首元素,rear指向隊尾;
上程式碼:
public class LinkedQueue { Node front;//隊頭指標,指向隊頭節點 Node rail;//隊尾指標,指向隊尾節點 int size = 0;//記錄佇列長度 //建構函式 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設定了next屬性,因為front節點與rail節點指向了同一個node節點,持有同一個結點的一個引用,因此front節點next屬性也被填充 rail.setNext(s); rail = s; size++; return true; } /** * 刪除元素,出佇列 * @return */ public boolean deleteQueue() { if (isEmpty()) { System.out.println("當前佇列為空"); 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(); } } /** * 首先連結串列底層是一個個結點 */ 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實現佇列的三種方法集合就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。