코딩테스트/JAVA

배열로 큐 구현

jeonghoe21 2025. 3. 3. 23:32
import java.io.*;

public class Main {
    private int[] queue; // 큐를 저장할 배열
    private int front; // 큐의 맨 앞을 가리키는 인덱스
    private int rear; // 큐의 맨 뒤를 가리키는 인덱스
    private int size; // 현재 큐의 크기

    // 🟢 큐 초기화 (생성자)
    public Main(int capacity) {
        queue = new int[capacity]; // 주어진 크기의 배열 생성
        front = 0; // front를 0으로 초기화
        rear = 0; // rear도 0으로 초기화
        size = 0; // 초기 크기는 0
    }

    // 🟢 push 연산: 큐의 rear에 새로운 원소 추가
    public void push(int x) {
        if (size == queue.length) { // 큐가 꽉 찬 경우
            throw new IllegalStateException("Queue is full");
        }
        queue[rear] = x; // rear 위치에 x 저장
        rear = (rear + 1) % queue.length; // rear를 한 칸 이동 (원형 큐)
        size++; // 큐 크기 증가
    }

    // 🟢 pop 연산: 큐의 front에서 원소 제거 후 반환
    public int pop() {
        if (size == 0) { // 큐가 비어있으면 -1 반환
            return -1;
        }
        int result = queue[front]; // front 위치의 원소 저장
        front = (front + 1) % queue.length; // front를 한 칸 이동 (원형 큐)
        size--; // 큐 크기 감소
        return result;
    }

    // 🟢 size 연산: 큐에 있는 원소 개수 반환
    public int size() {
        return size;
    }

    // 🟢 empty 연산: 큐가 비어있는지 확인
    public int empty() {
        return size == 0 ? 1 : 0;
    }

    // 🟢 front 연산: 큐의 맨 앞 원소 반환 (제거하지 않음)
    public int front() {
        if (size == 0) {
            return -1;
        }
        return queue[front];
    }

    // 🟢 back 연산: 큐의 맨 뒤 원소 반환 (제거하지 않음)
    public int back() {
        if (size == 0) {
            return -1;
        }
        return queue[(rear - 1 + queue.length) % queue.length]; // 원형 큐의 마지막 원소 계산
    }

    public static void main(String[] args) throws IOException {
        // 🟢 빠른 입력을 위한 BufferedReader 사용
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 🟢 빠른 출력을 위한 BufferedWriter 사용
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = Integer.parseInt(br.readLine()); // 명령어 개수 입력

        Main queue = new Main(n); // 입력된 크기로 큐 생성

        for (int i = 0; i < n; i++) {
            String command = br.readLine(); // 한 줄 입력받기
            String[] parts = command.split(" "); // 공백 기준으로 명령어 분리
            String cmd = parts[0]; // 명령어 추출

            switch (cmd) {
                case "push": // push X
                    int x = Integer.parseInt(parts[1]);
                    queue.push(x);
                    break;
                case "pop":
                    bw.write(queue.pop() + "\n");
                    break;
                case "size":
                    bw.write(queue.size() + "\n");
                    break;
                case "empty":
                    bw.write(queue.empty() + "\n");
                    break;
                case "front":
                    bw.write(queue.front() + "\n");
                    break;
                case "back":
                    bw.write(queue.back() + "\n");
                    break;
                default:
                    throw new IllegalArgumentException("Invalid command: " + cmd);
            }
        }

        // 🟢 출력 버퍼 비우기
        bw.flush();
        // 🟢 BufferedReader & BufferedWriter 닫기
        br.close();
        bw.close();
    }
}

'코딩테스트 > JAVA' 카테고리의 다른 글

배열로 스택 구현  (0) 2025.03.03
DFS, BFS  (0) 2025.03.03
요세푸스 문제  (0) 2025.03.02