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
}
}
'자료구조&알고리즘' 카테고리의 다른 글
[JAVA자료구조]이진트리 구현 (0) | 2024.08.28 |
---|---|
[JAVA자료구조] 노드로 구현한 이진트리(Binary) (0) | 2024.08.21 |
[JAVA자료구조]배열로 구현한 큐 (0) | 2024.08.20 |
[JAVA자료구조]1. 리스트-단순연결리스트 (0) | 2024.08.17 |
[JAVA자료구조] 1. List 구현 (0) | 2024.08.17 |