1. 程式人生 > >大話資料結構九:佇列的鏈式儲存結構(鏈佇列)

大話資料結構九:佇列的鏈式儲存結構(鏈佇列)

1. 鏈佇列的特點:

鏈佇列其實就是單鏈表,只不過它是先進先出的單鏈表,為了實現方便,程式中設定了隊頭(front),隊尾(rear)兩個指標。

2. Java使用連結串列實現佇列: 

//結點類,包含結點的資料和指向下一個節點的引用
public class Node<E> {
	private E data; // 資料域
	private Node<E> next; // 指標域儲存著下一節點的引用

	public Node() {
	}

	public Node(E data) {
		this.data = data;
	}

	public Node(E data, Node<E> next) {
		this.data = data;
		this.next = next;
	}

	public E getData() {
		return data;
	}

	public void setData(E data) {
		this.data = data;
	}

	public Node<E> getNext() {
		return next;
	}

	public void setNext(Node<E> next) {
		this.next = next;
	}
}
// Java實現鏈佇列
public class LinkedQueue<T> {
	private Node<T> front; // 記住隊頭結點
	private Node<T> rear; // 記住隊尾結點
	private int size; // 記住連結串列長度

	public LinkedQueue() {
		front = rear = null;
		size = 0;
	}

	// 將元素追加到佇列尾部
	public boolean enqueue(T data) {
		Node<T> newNode = new Node<T>(data);
		if (isEmpty()) { // 判斷佇列是否為空
			front = rear = newNode;
		} else {
			rear.setNext(newNode); // 將新進來的結點設定為尾結點
			rear = newNode;
		}
		size++;
		System.out.println(data + "入隊..");
		return true;
	}

	// 佇列頭部的第一個元素出隊
	public T dequeue() {
		T data = null;
		if (isEmpty()) {
			System.out.println("佇列為空,無法出隊..");
		} else {
			if (front.getNext() == null) { // 佇列中只有一個結點
				rear = null;
			}
			data = front.getData();
			front = front.getNext(); // 將原隊頭的下一個結點設定為隊頭
			System.out.println(data + "出隊..");
			size--;
		}
		return data;
	}

	// 獲取鏈佇列的長度
	public int size() {
		return size;
	}

	// 判斷鏈佇列是否為空
	public boolean isEmpty() {
		return size == 0;
	}
	
	// 清空鏈佇列
	public void clear() {
		front = rear = null;
		size = 0;
	}
	
	// 列印佇列中的元素
	public void display() {
		if (!isEmpty()) {
			Node<T> nextNode = front;
			for (int i = 0; i < size(); i++) {
				System.out.print(" " + nextNode.getData());
				nextNode = nextNode.getNext();
			}
		}
	}
	
	// 測試方法
	public static void main(String[] args) {
		LinkedQueue<String> queue = new LinkedQueue<String>();
		queue.enqueue("張三");
		queue.dequeue();
		queue.dequeue();
		queue.enqueue("李四");
		queue.enqueue("王五");
		queue.enqueue("趙六");
		queue.dequeue();
		queue.enqueue("田七");
		queue.dequeue();
		queue.enqueue("周八");
		System.out.println("佇列中元素個數為: " + queue.size());
		System.out.print("列印佇列中的元素: ");
		queue.display();
	}
}

3. 鏈佇列和迴圈佇列比較:

1.) 時間上:迴圈佇列事先申請好空間,使用期間不釋放。鏈佇列每次申請和釋放結點存在一些時間開銷,如果入隊出隊操作頻繁,鏈佇列效能稍差。

2.) 空間上:迴圈佇列必須有一個固定長度,所以就有了儲存元素個數和空間浪費的問題。鏈佇列不存在這個問題,所以在空間上更為靈活。

4. 什麼時候使用鏈佇列:

1.) 在可以確定佇列長度最大值的情況下,建議用迴圈佇列。

2.) 如果無法預估佇列的長度,則用鏈佇列 。