자료구조

Queue - Java

Stitchhhh 2025. 4. 28. 19:37

Queue

  • QueueFIFO(First In First Out, 선입선출) 방식으로 동작하는 자료구조입니다.
  • Java에서는 Queue 인터페이스를 통해 다양한 구현체(예: LinkedList, PriorityQueue)를 제공합니다.
  • 먼저 추가한 데이터가 가장 먼저 제거되는 특징이 있습니다.

주요 특징

자료구조 노드 기반(LinkedList) 또는 배열 기반(예: ArrayDeque)
크기 조정 필요에 따라 동적으로 크기를 조정 (특히 LinkedList 기반일 경우)
접근 속도 front와 rear에서 빠른 접근 가능 (O(1))
삽입/삭제 속도 front에서 삭제, rear에서 삽입은 빠름 (O(1))
중복 허용 O (같은 값을 여러 번 저장 가능)
null 허용 일부 구현체에서는 허용 (LinkedList는 허용, ArrayDeque는 허용하지 않음)

대표 메서드

package structure.queue;

import java.util.Queue;

public class QueueClass {

    private final Queue<Integer> queue;

    public QueueClass(Queue<Integer> queue) {
        this.queue = queue;
    }

    // 큐의 끝에 값을 추가합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public Queue<Integer> offer(int value) {
        this.queue.offer(value);
        return this.queue;
    }

    // 큐의 front 요소를 제거하고 반환합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public Integer poll() {
        return this.queue.poll();
    }

    // 큐의 front 요소를 반환합니다(제거하지 않음).
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public Integer peek() {
        return this.queue.peek();
    }

    // 큐의 모든 요소를 제거합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public void clear() {
        this.queue.clear();
    }

    // 큐가 비어 있는지 확인합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public boolean isEmpty() {
        return this.queue.isEmpty();
    }

    // 큐의 요소 개수를 반환합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public int size() {
        return this.queue.size();
    }

    // 큐에 지정된 값이 포함되어 있는지 확인합니다.
    // 시간 복잡도: O(n) (큐를 순차적으로 검색)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public boolean contains(int value) {
        return this.queue.contains(value);
    }

    // 큐에서 지정된 값을 제거합니다.
    // 시간 복잡도: O(n) (값을 찾은 후 제거)
    // 예외 발생: NullPointerException - queue가 null인 경우
    public Queue<Integer> remove(Integer value) {
        this.queue.remove(value);
        return this.queue;
    }
}

'자료구조' 카테고리의 다른 글

ArrayDeque - Java  (10) 2025.04.28
Deque - Java  (0) 2025.04.28
Stack - Java  (0) 2025.04.28
LinkedList - Java  (8) 2025.04.27
ArrayList - Java  (0) 2025.04.27