자료구조 : 원형큐

code++·2026년 8월 5일
import java.util.Arrays;
import java.util.Scanner;

public class js {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("저장할 큐 사이즈를 입력해주세요: ");
        int n = sc.nextInt();
        CircularQueue circularQueue = new CircularQueue(n);
        for (int i = 0; i < n-1; i++) {
            System.out.println("원형 큐에 넣을 사이즈를 입력해보세요");
            circularQueue.enqueue(sc.nextInt());
        }
        System.out.println("현재 원형 큐: "+circularQueue.toString());
    }
}
class CircularQueue {

    private int[] queue;
    private int front;
    private int rear;


    public CircularQueue(int size) {
        queue = new int[size];
        front = 0;
        rear = 0;
    }


    public boolean isFull() {
        return (rear + 1) % queue.length == front;
    }


    public boolean isEmpty() {
        return front == rear;
    }


    public void enqueue(int data) {

        if(isFull()) {
            throw new RuntimeException("Queue Full");
        }

        queue[rear] = data;
        rear = (rear + 1) % queue.length;
    }


    public int dequeue() {

        if(isEmpty()) {
            throw new RuntimeException("Queue Empty");
        }

        int data = queue[front];

        front = (front + 1) % queue.length;

        return data;
    }


    public int peek() {

        if(isEmpty()) {
            throw new RuntimeException("Queue Empty");
        }

        return queue[front];
    }
    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();

        int index = front;

        while(index != rear) {
            sb.append(queue[index]).append(" ");
            index = (index + 1) % queue.length;
        }

        return sb.toString();
    }
}

profile
일상

0개의 댓글