提供一个基于链表的优先级队列,为了简便,只存储整数,假设数值越大,优先级越高。
工作时该队列按照数值的大小排列,出队时出优先级别最高的元素。
这已经不是普通意义上的队列(先进先出),叫优先级队列只是习惯。
put:入队
get:出队
isEmpty:是否为空
普通队列请参见LinkedQueue,Queue
相对与另一个实现(PriorityQueue),这个优先级队列没有容量的限制。
Node是辅助类,提供节点的数据结构,为了简便,没有使用标准的set,get
class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
int value() {
return value;
}
Node next() {
return next;
}
void next(Node next) {
this.next = next;
}
}
class PriorityQueue {
private Node top;
void put(int value) {
Node node = new Node(value);
if(top == null || top.value() <= value) {
node.next(top);
top = node;
} else {
Node temp = top.next();
Node previous = top;
while(temp != null) {
if(temp.value() <= value) break;
previous = temp;
temp = temp.next();
}
node.next(previous.next());
previous.next(node);
}
}
int get() {
assert top != null;
int result = top.value();
top = top.next();
return result;
}
boolean isEmpty() {
return top == null;
}
//测试代码
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
assert q.isEmpty();
q.put(10);
q.put(5);
q.put(20);
assert !q.isEmpty();
assert q.get() == 20;
assert q.get() == 10;
assert q.get() == 5;
assert q.isEmpty();
}
}