큐 자료구조에서 데이터는 가장 먼저 들어온 데이터가 가장 먼저 나가는 구조를 취하고 있다.

package ex13;

import java.util.LinkedList;
import java.util.Queue;

public class QueueTest {
    public static void main(String[] args) {
        Queue<Integer> q = new LinkedList<>();

        for (int i = 0; i < 5; i++) {
            q.add(i);
        }

        System.out.println("큐의 요소: " + q);

        int e = q.remove();
        System.out.println("삭제된 요소: " + e);
        System.out.println(q);
    }
}

Untitled

우선 순위 큐

데이터를 정렬없이 삽입하여도 정렬된 상태로 원소들을 추출해줌

remove를 호출하면 가장 작은 원소를 호출함

자료를 가지고 있을 때 저장된 값이 정렬이 되어있는 구조는 아니지만,

add나 remove를 호출하면 가장 작은 원소가 효율적으로 정렬됨

우선 순위 큐

package ex13;

import java.util.PriorityQueue;

public class PriorityQueueTest {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(30);
        pq.add(80);
        pq.add(20);

        System.out.println(pq);
        System.out.println("삭제된 원소: " + pq.remove()); // 작은 숫자가 우선순위가 높다.
    }
}

Untitled