資料結構複習之【隊列】

來源:互聯網
上載者:User

隊列是先進先出的線性表;

隊列由於是線性表,因此也有順序儲存和鏈式儲存兩種實現方式;

一、順序儲存實現

由於隊列的特性是:從隊尾添加,從對頭刪除,因此如果讓數組的尾部用作隊尾,數組的頭部用作隊頭,則刪除元素時,時間複雜度為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;}}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.