자료구조&알고리즘

[JAVA자료구조] 배열로 구현한 스택

인생개발 이정환 2024. 8. 18. 09:28
import java.util.EmptyStackException;

public class ArrayStack<E> {
    private E[] stack;
    private int top;
    private int capacity;

    @SuppressWarnings("unchecked")
    public ArrayStack(int capacity) {
        this.capacity = capacity;
        stack = (E[]) new Object[capacity];
        top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == capacity - 1;
    }

    public void push(E item) {
        if (isFull()) {
            throw new StackOverflowError("Stack is full");
        }
        stack[++top] = item;
    }

    public E pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return stack[top--];
    }

    public E peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return stack[top];
    }

    public int size() {
        return top + 1;
    }

    public void clear() {
        top = -1;
    }

    public static void main(String[] args) {
        ArrayStack<Integer> stack = new ArrayStack<>(5);

        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println("Top element: " + stack.peek()); // 출력: Top element: 3
        System.out.println("Stack size: " + stack.size()); // 출력: Stack size: 3

        System.out.println("Popped element: " + stack.pop()); // 출력: Popped element: 3
        System.out.println("Top element: " + stack.peek()); // 출력: Top element: 2
        System.out.println("Stack size: " + stack.size()); // 출력: Stack size: 2

        stack.clear();
        System.out.println("Stack size after clear: " + stack.size()); // 출력: Stack size after clear: 0
    }
}