본문 바로가기
JAVA

[ JAVA ] Priority Queue ( 우선순위 큐 ) 총 정리

by 데구르르르 2021. 2. 5.
728x90

일반적인 자료구조의 큐는 FIFO ( First In First Out ) 선입선출 의 구조를 가지고 있습니다. 그러나 기존의 큐와는 다르게 우선순위 큐는 먼저 들어온 순서대로 나가는 것이 아니라 우선순위가 높은 엘리먼트가 먼저 나가는 구조를 가지고 있습니다. 기본적으로 힙 구조를 이용하여 구현하며 우선순위에 따라 최소 힙 / 최대 힙  으로 구현합니다. 내부 요소들은 힙 구조로 이진트리로 구성되어 있습니다.

  • 삽입 시 -> 마지막 노드에 삽입 후 부모 노드와 비교하며 Swap
  • 삭제 시 -> 우선순위가 가장 높은 루트 노드를 삭제 후 마지막 노드를 루트 노드에 올린 후 자식 노드들과 비교하며 Swap


PriorityQueue 자료구조를 사용하기 전 import java.util.* 필수!

import java.util.*; 



PriorityQueue 선언

import java.util.*; 

// int형 priorityQueue 선언 (우선순위가 낮은 숫자 순)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); 

//int형 priorityQueue 선언 (우선순위가 높은 숫자 순)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());



PriorityQueue 값 삽입

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); // int형 우선순위큐 선언

priorityQueue.add(1);     // priorityQueue에 값 1 추가
priorityQueue.add(2);     // priorityQueue에 값 2 추가
priorityQueue.offer(3);   // priorityQueue에 값 3 추가
priorityQueue.offer(5);   // priorityQueue에 값 5 추가



PriorityQueue  값 삭제

priorityQueue.pop();      // 우선순위 큐의 첫번째 값 반환 후 제거
priorityQueue.remove();   // 우선순위 큐의 첫번째 값 제거
priorityQueue.clear();    // 우선순위 큐의 전체 값 제거 (초기화)



PriorityQueue 의 맨 위 값 출력 ( 우선순위가 가장 높은 값 출력 )

priorityQueue.peek();     // priorityQueue의 가장 우선순위가 높은 값 출력
728x90

'JAVA' 카테고리의 다른 글

[ JAVA ] BufferedReader, BufferedWriter  (0) 2021.04.03
[ JAVA ] String to Int, Int to String 형변환  (0) 2021.02.07
[ JAVA ] Stack 총 정리  (0) 2021.02.02
[ JAVA ] Queue 총 정리  (0) 2021.01.31
[ JAVA ] Math.pow  (0) 2021.01.29

댓글