자료구조

스택 구현

leeeehhjj 2022. 3. 29. 14:31
public class Stack {
    private int ptr;
    private int max;
    private int[] stk;
    
    public class EmptyStackException extends RuntimeException {
        
    }
    
    public class OverflowStackException extends RuntimeException {
        
    }
    
    public Stack(int capacity) {
        ptr = 0;
        max = capacity;
        try {
            stk = new int[max];
        }catch (OutOfMemoryError e) {
            max = 0;
        }
    }
    
    public int push(int x) throws OverflowStackException {
        if (ptr >= max) 
            throw new OverflowStackException();
        return stk[ptr++] = x;
    }
    
    public int pop() throws EmptyStackException {
        if (ptr <= 0)
            throw new EmptyStackException();
        return stk[ptr--];
    }
    
    public int peek() throws EmptyStackException { //가장 꼭대기에 저장된 값 조회
        if (ptr <= 0)
            throw new EmptyStackException();
        return stk[ptr - 1];
    }
    
    public int indexOf(int x) { //x라는 값 존재하는지 검색
        for (int i = ptr -1; i >= 0; i--) {
            if (stk[i] == x)
                return i;
        }
        return -1;
    }
    
    public void clear() {
        ptr = 0;
    }
    
    public int capacity() {
        return max;
    }
    
    public int size() {
        return ptr;
    }
    
    public boolean isEmpty() {
        return ptr <= 0;
    }
    
    public boolean isFull() {
        return ptr >= max;
    }
    
    public void dump() { //스택 안 모든 값을 바닥에서 꼭대기까지 출력
        if (ptr <= 0)
            System.out.println("스택이 비어있습니다");
        else {
            for (int i = 0; i < ptr; i++) {
                System.out.println(stk[i] + " ");
            }
            System.out.println();
        }
    }
}