public class PriorityQueue {
public PriorityQueue() {}
class Node{
int value;
int priority;
Node next;
public Node(int value,int priority) {
this.value = value;
this.priority = priority;
}
}
private Node head;
public void push(int value,int priority) {
Node newNode = new Node(value,priority);
if(head == null) head = newNode;
else {
if(newNode.priority>head.priority) {
newNode.next = head;
head = newNode;
}else {
Node current = head;
while(current.next != null && current.next.priority > newNode.priority) current = current.next;
if(current.next == null) current.next = newNode;
else {
newNode.next = current.next;
current.next = newNode;
}
}
}
}
public Node pop() {
if(head != null) {
Node node = head;
head = head.next;
return node;
}
return null;
}
public Node peek() {
return head;
}
}
优先级队列的java实现
最新推荐文章于 2024-05-01 10:00:00 发布