자료구조 - Stack

code++·2024년 9월 27일
public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack(5);
        stack.isEmpty();
        stack.push(2);
        stack.push(3);
        stack.peek();
        stack.pop(3);
        stack.peek();
        stack.printAll();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.printAll();
    }
}
class Stack{
    int[] stackArray;
    int top;
    int size;

    //stack 생성자
    public Stack(int size) {
        this.stackArray = new int[size];
        this.top = -1;
    }
    public boolean isEmpty(){
        if (top == -1){
            System.out.println("stack is empty");
            return true;
        }
        return false;
    }
    public boolean isfull(){
        if(top == stackArray.length-1){
            System.out.println("stack is full");
            return true;
        }   return false;
    }

    public void pop(int data){
        if(top == stackArray.length-1){
            System.out.println("stack is empty");
        }
        stackArray[--top] =data;
    }
    public void push(int data){
        if(isfull()){
            System.out.println("stack is full");
        }
        stackArray[++top] = data;

    }
    //현재위치
    public void peek(){
        System.out.println("현재 위치 : " + top);
    }
    public void printAll(){
        if (isEmpty()) {
            System.out.println("스택이 비어 있습니다.");
            return;
        }
        System.out.println("스택 요소: ");

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

0개의 댓글