[java] 자바에서 스택 구현 방법은?

스택은 후입선출(LIFO) 원칙에 따라 데이터를 저장하는 자료구조입니다. 자바에서는 스택을 구현하기 위해 여러 가지 방법을 사용할 수 있습니다. 여기에는 배열을 사용한 방법과 연결 리스트를 사용한 방법이 있습니다.

  1. 배열을 사용한 스택 구현:
    public class Stack {
     private int maxSize;
     private int top;
     private int[] stackArray;
    
     public Stack(int size) {
         maxSize = size;
         stackArray = new int[maxSize];
         top = -1;
     }
    
     public void push(int item) {
         if (top < maxSize - 1) {
             stackArray[++top] = item;
         } else {
             System.out.println("Stack is full. Cannot push item.");
         }
     }
    
     public int pop() {
         if (top >= 0) {
             return stackArray[top--];
         } else {
             System.out.println("Stack is empty. Cannot pop item.");
             return -1;
         }
     }
    
     public int peek() {
         if (top >= 0) {
             return stackArray[top];
         } else {
             System.out.println("Stack is empty. Cannot peek item.");
             return -1;
         }
     }
    
     public boolean isEmpty() {
         return top == -1;
     }
    
     public boolean isFull() {
         return top == maxSize - 1;
     }
    }
    
  2. 연결 리스트를 사용한 스택 구현: ```java public class Node { int data; Node next;

    public Node(int data) { this.data = data; this.next = null; } }

public class Stack { private Node top;

public Stack() {
    top = null;
}

public void push(int item) {
    Node newNode = new Node(item);
    if (top == null) {
        top = newNode;
    } else {
        newNode.next = top;
        top = newNode;
    }
}

public int pop() {
    if (top == null) {
        System.out.println("Stack is empty. Cannot pop item.");
        return -1;
    }
    int item = top.data;
    top = top.next;
    return item;
}

public int peek() {
    if (top == null) {
        System.out.println("Stack is empty. Cannot peek item.");
        return -1;
    }
    return top.data;
}

public boolean isEmpty() {
    return top == null;
} } ```

이러한 방법으로 자바에서 스택을 구현할 수 있습니다. 각각의 구현 방법은 장단점을 가지고 있으니 필요에 맞게 선택하여 사용하면 됩니다.

추가로, 자바에서 스택을 사용하기 위해서는 위의 코드를 이용하여 객체를 생성한 후에 push, pop, peek 등의 메서드를 호출하여 사용하면 됩니다.

관련된 참고 자료: