์คํ(Stack)
์คํ์ ๋ฐ์ดํฐ๋ฅผ ์ผ์์ ์ผ๋ก ์ ์ฅํ๊ธฐ ์ํ ์๋ฃ๊ตฌ์กฐ๋ก, ๊ฐ์ฅ ๋์ค์ ๋ค์ด์จ ๋ฐ์ดํฐ๊ฐ ๊ฐ์ฅ ๋จผ์ ๋๊ฐ๋ ํ์
์ ์ถ(LIFO: Last In First Out) ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋ค.
ํต์ฌ ์์
์์ | ์ค๋ช
|
push() | ์คํ์ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํ๋ ์ฐ์ฐ |
pop() | ์คํ์์ ์ต์์ ๋ฐ์ดํฐ๋ฅผ ์ ๊ฑฐํ๊ณ ๋ฐํํ๋ ์ฐ์ฐ |
peek() | ์คํ์ ์ต์์ ๋ฐ์ดํฐ๋ฅผ ์กฐํํ๋ ์ฐ์ฐ |
isEmpty() | ์คํ์ด ๋น์ด์๋์ง ํ์ธํ๋ ์ฐ์ฐ |
size() | ์คํ์ ์ ์ฅ๋ ๋ฐ์ดํฐ ๊ฐ์๋ฅผ ๋ฐํํ๋ ์ฐ์ฐ |
์ง์ ๊ตฌํ ์์ ์ฝ๋
public class Stack<T> {
private Object[] elements;
private int size;
public Stack(int capacity) {
elements = new Object[capacity];
size = 0;
}
public void push(T item) {
if (size == elements.length) {
throw new IllegalStateException("Stack is full");
}
elements[size++] = item;
}
@SuppressWarnings("unchecked")
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
T item = (T) elements[--size];
elements[size] = null;
return item;
}
@SuppressWarnings("unchecked")
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return (T) elements[size - 1];
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
}
Java
๋ณต์ฌ
โข
์คํ์ฝ๋
public class Main {
public static void main(String[] args) {
Stack<String> stack = new Stack<>(10);
stack.push("์๋ฉ๋ฆฌ์นด๋
ธ");
stack.push("์นดํ๋ผ๋ผ");
stack.push("์นดํ๋ชจ์นด");
for (int i = 0; i < 3; i++) {
String item = stack.pop();
System.out.println(item);
}
System.out.println();
}
}
Java
๋ณต์ฌ
Java Collection Framework ์ฌ์ฉ ์์
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
// ๋ฐ์ดํฐ ์ถ๊ฐ
stack.push("First");
stack.push("Second");
stack.push("Third");
System.out.println("Stack size: " + stack.size()); // 3
System.out.println("Top element: " + stack.peek()); // Third
// ๋ฐ์ดํฐ ์ ๊ฑฐ
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
}
}
Java
๋ณต์ฌ




