Android-演算法-優先順序佇列
阿新 • • 發佈:2018-12-14
class PriorityQueue { private long[] a = null; private int nItems = 0; private int maxSize = 0; public PriorityQueue(int maxSize) { a = new long[maxSize]; this.maxSize = maxSize; nItems = 0; } public void insert(long l) { //優先順序佇列的插入不是隊尾,而是選擇一個合適的按照某種順序插入的 //當佇列長度為0時,如下 //不為0時,將所有比要插入的數小的資料後移,這樣大的數就在佇列的頭部了 int i = 0; if (nItems == 0) { a[0] = l; } else { for (i = nItems - 1; i >= 0; i--) { if (l < a[i]) a[i + 1] = a[i]; else break; } a[i + 1] = l; } nItems++; } public long remove() { //移出的是陣列最上端的數,這樣減少陣列元素的移動 return a[--nItems]; } public boolean isEmpty() { return (nItems == 0); } public boolean isFull() { return (nItems == maxSize); } public int size() { return nItems; } } public class duilie { // 佇列體類 private duilie s; private String data; duilie(String data) { this.data = data; } public String getData() { return data; } public void setData(String data) { this.data = data; } public duilie getS() { return s; } public void setS(duilie s) { this.s = s; } } public class duiliecz { // 佇列操作類 /** * @param args */ private int i = 0; // 佇列長 private duilie top = new duilie(""); // 佇列頭 private duilie end = new duilie(""); // 佇列尾 public void add(String s) { // 新增佇列 duilie m = new duilie(s); if (i != 0) { m.setS(top.getS()); top.setS(m); } else { top.setS(m); end.setS(m); } i++; }