자료구조 - Queue

code++·2024년 9월 27일

class Node{
    int data;
    Node next;

    int size;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}public class queue {
    int size;
    Node front;
    Node rear;

    public queue() {
        this.front = null;
        this.rear = null;
        this.size = 0;
    }


    public boolean isEmpty() {
        return (size == 0);
    }

    public void enqueue(int data) {
        Node newNode = new Node(data);
        if (isEmpty()) {
            front = newNode;
            rear = newNode;
        }else{
            rear.next = newNode;
            rear = newNode;
        }
        size++;
    }

    public int dequeue() {
        if (isEmpty()) {
            System.out.println("큐가 비어 있습니다.");
            return -1;  // 에러 코드
        }
        int dequeuedValue = front.data; // 제거할 값 저장
        front = front.next; // front를 다음 노드로 갱신
        size--; // 크기 감소
        if (isEmpty()) {
            rear = null; // 큐가 비어 있으면 rear도 null로 설정
        }
        return dequeuedValue; // 제거한 값 반환
    }

    public int peek() {
        if (isEmpty()) {
            System.out.println("큐가 비어있네?");
            return -1;
        }
        return front.data;
    }

    public int size() {
        return size;
    }

    public void printAll() {
        if (isEmpty()) {
            System.out.println("큐가 비어있다");
            return;
        }
        Node current = front; // 현재 노드를 front로 초기화
        System.out.print("현재 큐 상태: ");
        while (current != null) { // 현재 노드가 null이 아닐 동안 반복
            System.out.print(current.data + " "); // 데이터 출력
            current = current.next; // 다음 노드로 이동
        }
        System.out.println(); // 줄 바꿈
    }

    public static void main(String[] args) {
        queue q = new queue();
        q.enqueue(1);
        q.enqueue(2);
        q.enqueue(3);
        q.enqueue(5);
        q.printAll();

    }
}
profile
일상

0개의 댓글