๐Ÿ’ก (Java) ํ Queue ์ •๋ฆฌ

๋ฐ•ํ˜„์•„ยท2024๋…„ 11์›” 7์ผ
0

๊ธฐ์ดˆ

๋ชฉ๋ก ๋ณด๊ธฐ
30/31

๐Ÿ’ก ํ Queue ์ •๋ฆฌ

์ž๋ฐ”์—์„œ ํ(Queue)๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ์ž๋ฃŒ ๊ตฌ์กฐ๋กœ, ์ผ๋ฐ˜์ ์œผ๋กœ FIFO (First In, First Out) ๋ฐฉ์‹์œผ๋กœ ์ž‘๋™ํ•œ๋‹ค. ํ๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์ž๋ฐ”์—์„œ๋Š” Queue ์ธํ„ฐํŽ˜์ด์Šค์™€ ๊ทธ ๊ตฌํ˜„์ฒด์ธ LinkedList, PriorityQueue, ArrayDeque ๋“ฑ์„ ์‚ฌ์šฉํ•œ๋‹ค.

LinkedList๋ฅผ ์ด์šฉํ•œ ํ ์˜ˆ์‹œ

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

public class QueueExample {
    public static void main(String[] args) {
        // ํ ์ƒ์„ฑ
        Queue<String> queue = new LinkedList<>();

        // ํ์— ์š”์†Œ ์ถ”๊ฐ€ (offer ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ)
        queue.offer("Apple");
        queue.offer("Banana");
        queue.offer("Cherry");

        // ํ์—์„œ ์š”์†Œ ์ œ๊ฑฐ (poll ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ)
        System.out.println("Removed: " + queue.poll());  // Apple
        System.out.println("Removed: " + queue.poll());  // Banana

        // ํ์—์„œ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ ํ™•์ธ (peek ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ)
        System.out.println("Next in queue: " + queue.peek());  // Cherry

        // ํ๊ฐ€ ๋น„์—ˆ๋Š”์ง€ ํ™•์ธ
        System.out.println("Is the queue empty? " + queue.isEmpty());  // false
    }
}

์ด ์˜ˆ์‹œ์—์„œ LinkedList๋Š” Queue ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ๋Œ€ํ‘œ์ ์ธ ํด๋ž˜์Šค์ด๋‹ค. ํ์˜ ์•ž์ชฝ์—์„œ ์‚ฝ์ž…๊ณผ ์‚ญ์ œ๊ฐ€ ๋น ๋ฅด๊ธฐ ๋•Œ๋ฌธ์—, ๋Œ€๊ธฐ์—ด์ด๋‚˜ ์ž‘์—… ๊ด€๋ฆฌ ๋“ฑ ๋‹ค์–‘ํ•œ ์‹œ๋‚˜๋ฆฌ์˜ค์—์„œ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉ๋œ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€

Powered by GraphCDN, the GraphQL CDN