CS 기초/자료구조

알고리즘-자료구조-스택 구현

꿈꾸는 아이 2025. 5. 7. 19:15

자료구조 구현(자바)

  • 스택
public class MyStack {
    private int[] data;
    private int top;
    
    public MyStack(){
        data = new int[10];
        top = -1;
    }
    
    public void push(int value){
        if(top == data.length -1){
            resize();
        }
        data[++top] = value;
    }
    
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("스택이 비어 있습니다.");
        }
        return data[top--];
    }
    
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("스택이 비어 있습니다.");
        }
        return data[top];
    }
    
    public boolean isEmpty(){
        return top == -1;
    }
    
    public int size(){
        return top + 1;
    }
    
    private void resize(){
        int[] newData = new int[data.length * 2];
        for(int i = 0; i < data.length; i++){
            newData[i] = data[i];
        }
        data = newData;
    }
}