数据结构之优先队列
priority queue
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。通常采用堆数据结构来实现。
属性
优先队列的属性和队列类似主要包括以下部分
int size() 返回队列的长度
boolean add(E) / boolean offer(E) 向队列尾部中添加元素
E remove()/E poll() 从队列头取出元素并删除
E element()/E peek() 从队列头取出元素但不删除
添加时若使用add当添加的元素超过了Queue的长度会报错,当调用offer时不会报错,会返回false
去除元素时,若使用remove(),当Queue为空,会报错,当调用poll()会返回null
注:LinkedList即实现了List接口,又实现了Queue接口,但是,在使用的时候,如果我们把它当作List,就获取List的引用,如果我们把它当作Queue,就获取Queue的引用
// 这是一个List:
List<String> list = new LinkedList<>();
// 这是一个Queue:
Queue<String> queue = new LinkedList<>();
简单示例
package top.ligongd.structure;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue<User> priorityQueue = new PriorityQueue<>(new UserComparator());
priorityQueue.offer(new User("V12", 12));
priorityQueue.offer(new User("we", 13));
priorityQueue.offer(new User("V13", 14));
User user1 = priorityQueue.poll();
User user2 = priorityQueue.poll();
User user3 = priorityQueue.poll();
System.out.println(user1.getName());
System.out.println(user2.getName());
System.out.println(user3.getName());
}
}
class User{
private String name;
private int age;
public User(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class UserComparator implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
if(o1.getName().charAt(0) == o2.getName().charAt(0))
return o1.getName().compareTo(o2.getName());
if(o1.getName().startsWith("V"))
return -1;
else
return 1;
}
}
V12
V13
we
Process finished with exit code 0