
FIFO 형식으로 처리되는 큐(Queue)와 달리우선순위가 높은 요소가 먼저 처리되는 자료구조
완전이진트리 형태의 자료구조
10
/ \
20 15
/ \ / \
40 50 30 25
50
/ \
30 40
/ \ / \
10 20 35 25
java.util 패키지에 포함된 클래스 사용선언
PriorityQueue<T> pq = new PriorityQueue<>();
삽입 및 삭제
PriorityQueue<Integer> pq = new PriorityQueue<>();
// 삽입
pq.add(10);
pq.add(20);
pq.add(15);
// 삭제
pq.poll(); // 10
pq.poll(); // 15
pq.poll(); // 20
최대 힙
Comparator 사용해 최대 힙 구현 가능PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
// 삽입
pq.add(10);
pq.add(20);
pq.add(15);
// 삭제
pq.poll(); // 20
pq.poll(); // 15
pq.poll(); // 10
사용자 정의
PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.charAt(1) - o2.charAt(1);
}
};);
// 삽입
pq.add("apple");
pq.add("banana");
pq.add("cold");
pq.add("error");
// 삭제
pq.poll(); // banana
pq.poll(); // cold
pq.poll(); // apple
pq.poll(); // error