알고리즘 공부 중에 새롭게 알게 된 자료구조인 Priority Queue에 대해 정리했습니다.
Queue 인터페이스를 구현한 클래스offer(E e) → 요소가 우선순위에 맞게 배치됨poll() → 가장 높은 우선순위(최소값/Comparator 기준 최우선) 요소를 꺼냄peek() → 가장 높은 우선순위 요소 확인 (삭제 X)null 요소 저장 불가PriorityBlockingQueue 사용)iterator()로 전체를 조회하면 우선순위 순서대로 보장되지 않음poll()로 하나씩 꺼내야 함)PriorityQueue() → 기본(자연 순서)PriorityQueue(Comparator<? super E> comparator) → 사용자 정의 정렬 기준 지정 가능import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Comparator;
public class QueueExample {
public static void main(String[] args) {
// ================================
// 1. 일반 Queue (FIFO)
// ================================
Queue<Integer> normalQueue = new LinkedList<>();
normalQueue.offer(3);
normalQueue.offer(1);
normalQueue.offer(2);
System.out.println("일반 Queue (FIFO):");
while (!normalQueue.isEmpty()) {
System.out.print(normalQueue.poll() + " ");
}
// 출력: 3 1 2 (삽입 순서 그대로)
// ================================
// 2. PriorityQueue (기본: 최소 힙)
// ================================
Queue<Integer> minHeapQueue = new PriorityQueue<>();
minHeapQueue.offer(3);
minHeapQueue.offer(1);
minHeapQueue.offer(2);
System.out.println("\n\nPriorityQueue (Min Heap, 기본):");
while (!minHeapQueue.isEmpty()) {
System.out.print(minHeapQueue.poll() + " ");
}
// 출력: 1 2 3 (값이 작은 순)
// ================================
// 3. PriorityQueue (최대 힙, Comparator 사용)
// ================================
Queue<Integer> maxHeapQueue = new PriorityQueue<>(Comparator.reverseOrder());
maxHeapQueue.offer(3);
maxHeapQueue.offer(1);
maxHeapQueue.offer(2);
System.out.println("\n\nPriorityQueue (Max Heap, Comparator):");
while (!maxHeapQueue.isEmpty()) {
System.out.print(maxHeapQueue.poll() + " ");
}
// 출력: 3 2 1 (값이 큰 순)
}
}
읽어주셔서 감사합니다.
[Java] Priority Queue(우선 순위 큐)
[JAVA] PriorityQueue 우선순위 큐 사용법
[Java/자료구조] 선형구조 - 큐(Queue) 이해하기: 일반 큐, 우선순위 큐(Priority Queue) 이해하기