티스토리 뷰

JAVA

[JAVA] Stack int 배열로 직접 구현해보기

개발중인 감자 2023. 8. 8. 12:50

✏️ ArrayStack.java

public class ArrayStack {
    int[] stack;
    int top;
    int array_size = 10;
    static final int ERROR_NUM = Integer.MAX_VALUE;

    ArrayStack() {
        top = 0;
        stack = new int[array_size];
    }

    ArrayStack(int size) {
        top = 0;
        stack = new int[size];
        array_size = size;
    }

    public void push(int data) {
        if (isFull()) {
            return;
        }
        stack[top++] = data;
    }

    public int pop() {
        if (isEmpty()) return ERROR_NUM;
        return stack[--top];
    }

    public int peek() {
        if (isEmpty()) return ERROR_NUM;
        return stack[top-1];
    }

    public void printAll() {
        if (isEmpty()) return;
        
        System.out.println("= stack printAll =");
        for (int i = 0; i < top; i++) {
            System.out.print(stack[i] + " ");
        }
        System.out.println();
    }

    public boolean isFull() {
        if (top == array_size) {
            System.out.println("stack is full");
            return true;
        }
        return false;
    }

    public boolean isEmpty() {
        if (top == 0) {
            System.out.println("stack is empty");
            return true;
        }
        return false;
    }

}

 

✏️ ArrayStackTest.java

public class ArrayStackTest {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(3);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.printAll();
        System.out.println("stack pop(): " +stack.pop());
        System.out.println("stack pop(): " +stack.pop());
        System.out.println("stack pop(): " +stack.pop());
        System.out.println("stack pop(): " +stack.pop());
        stack.push(100);
        stack.printAll();

        stack = new ArrayStack();
        for (int i = 1; i <= 15; i++) {
            stack.push(i);
        }
        stack.printAll();

    }
}