Java 우선순위 큐

yshjft·2022년 12월 19일
0

Java, OOP

목록 보기
20/27
import java.util.PriorityQueue;

public class Main {
    private static class Node {
        private int value;

        public Node(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

    public static void main(String[] args) {
        // 기본(min-heap)
        System.out.println("====================");
        PriorityQueue<Integer> defaultPq = new PriorityQueue<>();
        defaultPq.add(1);
        defaultPq.add(2);
        defaultPq.add(3);

        /**
         * 1
         * 2
         * 3
         */
        while (!defaultPq.isEmpty()) {
            System.out.println(defaultPq.poll());
        }

        // min-heap
        System.out.println("====================");
        PriorityQueue<Node> minHeap = new PriorityQueue<>((n1, n2) -> n1.getValue() - n2.getValue());
        minHeap.add(new Node(100));
        minHeap.add(new Node(10));
        minHeap.add(new Node(1));

        /**
         * 1
         * 10
         * 100
         */
        while (!minHeap.isEmpty()) {
            Node node = minHeap.poll();
            System.out.println(node.getValue());
        }

        // maxHeap
        System.out.println("====================");
        PriorityQueue<Node> maxHeap = new PriorityQueue<>((n1, n2) -> n2.getValue() - n1.getValue());
        maxHeap.add(new Node(100));
        maxHeap.add(new Node(10));
        maxHeap.add(new Node(1));

        /**
         * 100
         * 10
         * 1
         */
        while (!maxHeap.isEmpty()) {
            Node node = maxHeap.poll();
            System.out.println(node.getValue());
        }
    }
}
profile
꾸준히 나아가자 🐢

0개의 댓글