CS 기초/자료구조

알고리즘-자료구조-덱-구현

꿈꾸는 아이 2025. 5. 8. 18:01

자료구조 구현(자바)

public class MyDeque {
    private int[] data;
    private int front;
    private int rear;
    private int size;

    public MyDeque(){
        data = new int[10];
        front = 0;
        rear = 0;
        size = 0;
    }

    public void addFirst(int value){
        if(size == data.length){
            resize();
        }

        front = (front-1+data.length) % data.length;
        data[front] = value;
        size++;
    }
    public void addLast(int value){
        if(size == data.length){
            resize();
        }

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

    public int removeFirst(){
        if(isEmpty()){
            throw new RuntimeException("덱이 비어 있습니다.");
        }
        int value = data[front];
        front = (front + 1) % data.length;
        size--;
        return value;
    }
    public int removeLast(){
        if(isEmpty()){
            throw new RuntimeException("덱이 비어 있습니다.");
        }
        rear = (rear - 1 + data.length) % data.length;
        int value = data[rear];
        size--;
        return value;
    }

    public int peekFirst(){
        if (isEmpty()) {
            throw new RuntimeException("덱이 비어 있습니다.");
        }
        return data[front];
    }
    public int peekLast(){
        if (isEmpty()) {
            throw new RuntimeException("덱이 비어 있습니다.");
        }
        return data[(rear - 1 + data.length)%data.length];
    }

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

    public int size(){
        return size;
    }

    private void resize(){
        int[] newData = new int[data.length * 2];
        for(int i = 0; i < size; i++){
            newData[i] = data[(front + i) % data.length];
        }

        data = newData;
        front = 0;
        rear = size;
    }
}

'CS 기초 > 자료구조' 카테고리의 다른 글

알고리즘-자료구조-해시  (0) 2025.05.08
알고리즘-자료구조-덱  (0) 2025.05.08
알고리즘-자료구조-큐 구현  (1) 2025.05.07
알고리즘-자료구조-큐  (0) 2025.05.07
알고리즘-자료구조-스택 구현  (0) 2025.05.07