자료구조 - Stack

code++·2024년 9월 27일
public class stack {
    int maxstacksize;//stack 최대 사이즈
    int[] stackArrary;//스택 배열
    int top;//현위치

    public stack(int size) {
        this.maxstacksize = size;
        this.stackArrary = new int[maxstacksize];
        this.top = -1;
    }

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

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

    public void push(int data) {
        if (isfull()) {
            System.out.println("스택이 꽉찼다.");
        } else{
            stackArrary[++top] = data;
        }
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("스택이 비어있다.");
            return -1;
        }
        return stackArrary[top--];
    }

    public int peek() {
        return stackArrary[top];
        //return stackArray[maxstacksize-1];
    }

    public void size() {
        System.out.println("현재 스택에 차있는 크기는 : "+(top+1)+"입니다.");
    }
    public void printAll() {
        if (isEmpty()) {
            System.out.println("스택이 비어 있습니다.");
            return;
        }
        System.out.println("스택 요소: ");

        for (int i = top; i >= 0; i--) {
            System.out.println(stackArrary[i] + " ");  // 최상위 요소부터 출력
        }
        System.out.println();  // 줄 바꿈
    }

    public static void main(String[] args) {
        stack st = new stack(5);

        st.push(1);
        st.push(2);
        st.push(3);
        st.printAll();

        st.size();
        st.peek();

        st.pop();
        st.printAll();
    }

}
profile
일상

0개의 댓글