Java數據結構--鏈式隊列

一、簡介

1.1 概念

隊列簡稱隊–他同堆棧一樣,也是一種運算受限的線性表,其限制是僅允許在表的一端進行插入,而在表的另一端進行刪除;
在隊列中把插入數據元素的一端稱爲隊尾,刪除數據元素的一端稱爲隊頭
向隊尾插入元素稱爲進隊和入隊,新元素入隊後成爲新的隊尾元素;從隊列中刪除元素稱爲離隊或出隊,元素出隊後,其後續元素成爲新的隊頭元素;
由於隊列的插入和刪除操作分別在隊尾和隊頭進行,每個元素必然按照進入的次序離隊,也就是說先進隊的元素必然先離隊,所以稱隊列爲先進先出表

鏈式隊列

1.2 結構圖

在這裏插入圖片描述

二、簡單實現

public class LinkQueue implements Queue {

    Node front; //隊頭
    Node rear;  //隊尾
    int count; //計數器

    public LinkQueue() {
        init();
    }

    public void init() {
        front = rear = null;
        count = 0;
    }

	/**
	* 在隊尾追加元素
	*/
    public void append(Object obj) throws Exception {
        Node node = new Node(obj, null);

        //如果當前隊列不爲空。
        if (rear != null) {
            rear.next = node; //隊尾結點指向新結點
        }

        rear = node; //設置隊尾結點爲新結點

        //說明要插入的結點是隊列的第一個結點
        if (front == null) {
            front = node;
        }
        count++;
    }

	/**
	* 刪除最後一個元素
	*/
    public Object delete() throws Exception {
        if (isEmpty()) {
            new Exception("隊列已空!");
        }
        Node node = front;
        front = front.next;
        count--;
        return node.getElement();
    }

	/**
	* 獲取隊頭
	*/
    public Object getFront() throws Exception {
        if (!isEmpty()) {
            return front.getElement();
        } else {
            return null;
        }
    }

	/**
	* 判斷隊列是否爲空
	*/
    public boolean isEmpty() {
        return count == 0;
    }
}
//結點類
public class Node {

    Object element; //數據域
    Node next;  //指針域

    //頭結點的構造方法
    public Node(Node nextval) {
        this.next = nextval;
    }

    //非頭結點的構造方法
    public Node(Object obj, Node nextval) {
        this.element = obj;
        this.next = nextval;
    }

    //獲得當前結點的後繼結點
    public Node getNext() {
        return this.next;
    }

    //獲得當前的數據域的值
    public Object getElement() {
        return this.element;
    }

    //設置當前結點的指針域
    public void setNext(Node nextval) {
        this.next = nextval;
    }

    //設置當前結點的數據域
    public void setElement(Object obj) {
        this.element = obj;
    }

    public String toString() {
        return this.element.toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章