隊列是先進先出的線性表;
隊列由於是線性表,因此也有順序儲存和鏈式儲存兩種實現方式;
一、順序儲存實現
由於隊列的特性是:從隊尾添加,從對頭刪除,因此如果讓數組的尾部用作隊尾,數組的頭部用作隊頭,則刪除元素時,時間複雜度為O(n);
因此我們需要用迴圈數組實現,並且維護兩個屬性 front、rear,front用來記錄隊頭的位置,rear記錄隊尾的下一個位置;比如:
這樣能夠充分利用數組的空間,但是預先規定了空間就不能再改變;
代碼實現如下:
package org.xiazdong.list;public class MyArrayQueue<T> {private int front;private int rear;private int length;private T[] t;public MyArrayQueue(){front = rear = length = 0;t = (T[])new Object[20];}public void append(T e) throws Exception{if(length==t.length){throw new QueueOverFlowException();}length++;t[rear] = e;rear = (rear+1)%t.length;}public T remove() throws Exception{if(length<=0){throw new QueueOffFlowException();}T e = t[front];length--;front = (front + 1)%t.length;return e;}public int getSize(){return length;}}class QueueOverFlowException extends Exception{public QueueOverFlowException(){super();}@Overridepublic String getMessage() {return "隊列溢出";}}class QueueOffFlowException extends Exception{public QueueOffFlowException(){super();}@Overridepublic String getMessage() {return "隊列空";}}
二、鏈式儲存實現
鏈式儲存簡單的說就是單鏈表+front、rear指標;
front指向頭結點,rear指向最後一個節點;
回顧一下頭結點的定義:不具有任何意義的節點,為了操作單鏈表方便而使用;
代碼實現如下:
package org.xiazdong.list;public class MyListQueue<T> {private BeginNode front;private Node rear;public MyListQueue(){front = new BeginNode(0,null);rear = front;}public void append(T e){Node n = new Node(e,null);rear.next = n;rear = n;front.elem++;}public T remove() throws Exception{if(front.elem<=0){throw new Exception();}T e = front.next.elem;front.next = front.next.next;front.elem--;if(front.elem==0){rear = front;}return e;}class Node {private T elem;Node next;public Node() {elem = null;next = null;}public Node(T elem, Node next) {this.elem = elem;this.next = next;}}class BeginNode extends Node {int elem;public BeginNode(int elem, Node next) {this.elem = elem;this.next = next;}}}