基於有序連結串列實現的優先佇列
阿新 • • 發佈:2018-12-10
博主最近在苦讀演算法第四版,在第二章第四節的優先佇列的實現中,作者提到了可以用有序或無序連結串列實現優先佇列,博主在網上大致查閱了一下,好像沒有現成的java程式碼(泛型的),於是自己根據找到的程式碼簡單修改並實現了一下,特此記錄一下。
/*定義結點的抽象資料型別*/ class Node<Key extends Comparable<Key>> { public Key key; public Node next; public void displayNode() { System.out.print(key+" "); } } /*定義了一個有序連結串列,連結串列表示的是一列元素*/ class LinkedList<Key extends Comparable<Key>> { private Node first; //棧頂(最近新增的元素) public LinkedList() { first = null; } /*向連結串列中新增元素的push方法保證所有元素為逆序*/ public void push(Key key) { Node newLink = new Node(); newLink.key = key; Node previous = null; Node current = first; //得到資料插入的位置 while(current != null && less((Key)newLink.key,(Key)current.key)) { previous = current; current = current.next; } if(previous == null) { first = newLink; } //移動結點到指定位置 else { previous.next = newLink; } newLink.next = current; } private boolean less(Key v, Key w) { return v.compareTo(w) < 0; } public Key delete() { Key tmp = (Key)first.key; first = first.next; return tmp; } public void displayLinList() { Node current = first; while(current != null) { current.displayNode(); current = current.next; } } } public class OrderedLinkedlistMaxPQ { public static void main(String[] args) { LinkedList ll= new LinkedList(); ll.push("t"); ll.push("i"); ll.push("a"); ll.push("k"); ll.push("j"); ll.push("p"); ll.push("d"); ll.push("f"); ll.push("m"); ll.push("s"); ll.push("z"); ll.push("b"); ll.displayLinList(); System.out.println(); ll.delete(); ll.displayLinList(); } }