【資料結構】帶有尾指標的連結串列:連結串列實現佇列
阿新 • • 發佈:2018-12-14
前面寫了用動態陣列實現佇列,現在我將用帶有尾指標的連結串列實現佇列。
我們知道佇列需要在兩端進行操作,如果是以普通連結串列進行底層實現的佇列,在入隊時需要找到最後一個節點才能進行新增元素,這樣相當於遍歷一遍連結串列,從而造成巨大的時間浪費。
為了解決這個問題,我們引入了尾指標的概念,即始終使用tail作為最後一個節點,這樣我們在入隊時就能直接操作,無需在連結串列中遍歷尋找最後一個節點的位置。
-------------------------------------------------------------------------------------------------------------------------------------------------
實現介面:Queue<E>
實現類:LinkedListQueue<E>
因為帶有尾指標,故不再複用前面寫的不帶有尾指標的LinkedList連結串列類。
-------------------------------------------------------------------------------------------------------------------------------------------------
public class LinkedListQueue<E> implements Queue<E> { /* * 建立只允許本類呼叫的內部類(節點類) */ private class Node { public E e; public Node next; // 內部類構造方法 public Node(E e, Node next) { this.e = e; this.next = next; } public Node(E e) { this.e = e; this.next = null; } public Node() { this(null, null); } @Override public String toString() { return e.toString(); } } private Node dummyHead, tail;// 虛擬頭結點和尾節點 private int size; // 帶有尾指標的連結串列構造方法 public LinkedListQueue() { dummyHead = new Node(); tail = new Node(); size = 0; } @Override public void enqueue(E e) { if (tail.e== null) {// 尾節點為空,也意味著頭節點為空 tail = new Node(e); dummyHead.next = tail;// 只含一個元素,此時頭結點等於尾節點 } else { tail.next = new Node(e); tail = tail.next; } size++; } @Override public E dequeue() { if (isEmpty()) throw new IllegalArgumentException("操作失敗!連結串列為空!"); Node head = dummyHead.next; dummyHead.next = head.next; head.next = null; size--; return head.e; } @Override public E getFront() { return dummyHead.next.e; } @Override public int getSize() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public String toString() { StringBuilder res = new StringBuilder(); res.append("Queeu: top "); for (Node cur = dummyHead.next; cur != null; cur = cur.next) res.append(cur + "->"); res.append("NULL tail"); return res.toString(); } }