본문 바로가기

JAVA/Algorithm

스택(Stack)

SMALL
package stack;

public class Stack {
    private int maxSize;
    private int top;
    private int[] array;

    public Stack(int capacity) {
        maxSize = capacity;
        top = -1;
        array = new int[maxSize];
    }

    public void push(int item) {
        if (top == maxSize - 1) {
            System.out.println("Stack is full. Cannot push item: " + item);
        } else {
            array[++top] = item;
        }
    }

    public int pop() {
        if (top == -1) {
            System.out.println("Stack is empty.");
            return -1;
        } else {
            return array[top--];
        }
    }

    public int peek() {
        if (top == -1) {
            System.out.println("Stack is empty.");
            return -1;
        } else {
            return array[top];
        }
    }

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

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

위의 코드는 Stack 클래스를 정의하고, 배열을 이용하여 스택을 구현합니다. maxSize는 스택의 최대 크기를 나타내며, top은 스택의 상단 인덱스를 추적합니다. array는 실제 데이터 요소들을 저장하는 배열입니다.

 

push() 메서드는 스택에 요소를 추가하고, pop() 메서드는 스택의 상단 요소를 제거하고 반환합니다.

 

peek() 메서드는 상단 요소를 반환하지만 제거하지는 않습니다. isEmpty() 메서드는 스택이 비어있는지 여부를 확인하며, size() 메서드는 스택에 저장된 요소의 개수를 반환합니다.

 

package stack;

public class Client {
    public static void main(String[] args) {
        Stack st = new Stack(5);
        st.push(10);
        st.push(20);
        st.push(30);

        System.out.println("Stack size: " + st.size());
        System.out.println("Top Element: " + st.peek());

        int popedElement = st.pop();

        System.out.println("Poppend element: " + popedElement);
        System.out.println("Is stack empty? " + st.isEmpty());
    }
}

 

Stack 객체를 생성하고 push() 메서드로 요소를 추가한 후, size() 메서드로 스택의 크기를 확인하고 peek() 메서드로 상단 요소를 출력합니다.

 

그리고 pop() 메서드로 상단 요소를 제거하고 반환한 후 해당 값을 출력합니다. 마지막으로 isEmpty() 메서드로 스택이 비어있는지 여부를 출력합니다.

 

* reference source : https://gitlab.com/jeongjaeha/algorithm.git

LIST

'JAVA > Algorithm' 카테고리의 다른 글

자바 재귀호출  (0) 2023.05.30
더블 링크드 리스트(Doubly Linked List)  (0) 2023.05.25
단방향 연결 리스트( Singlely Linked List)  (0) 2023.05.24
자바 알고리즘 Queue  (0) 2023.05.17
빅오 표기법(Big O notation)  (0) 2023.05.16