Java์์ Stack ํด๋์ค๋ LIFO(Last-In, First-Out) ๊ตฌ์กฐ๋ฅผ ์ ๊ณตํ์ฌ, ๋ง์ง๋ง์ ์ถ๊ฐ๋ ์์๊ฐ ๊ฐ์ฅ ๋จผ์ ์ ๊ฑฐ๋๋ ๋ฐฉ์์ผ๋ก ์๋ํ๋ค. Stack ํด๋์ค๋ java.util ํจํค์ง์ ํฌํจ๋์ด ์๋ค.
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// ์คํ ์์ฑ
Stack<Integer> stack = new Stack<>();
// ์์ ์ถ๊ฐ(push)
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("์คํ: " + stack); // [10, 20, 30]
// ๋งจ ์ ์์ ํ์ธ(peek)
int top = stack.peek();
System.out.println("๋งจ ์ ์์: " + top); // 30
// ๋งจ ์ ์์ ์ ๊ฑฐ(pop)
int removedElement = stack.pop();
System.out.println("์ ๊ฑฐ๋ ์์: " + removedElement); // 30
System.out.println("์คํ (pop ํ): " + stack); // [10, 20]
// ์คํ์ด ๋น์ด ์๋์ง ํ์ธ
boolean isEmpty = stack.isEmpty();
System.out.println("์คํ์ด ๋น์ด ์์ต๋๊น? " + isEmpty); // false
// ์คํ์์ ์์ ์ฐพ๊ธฐ (1-based index ๋ฐํ)
int position = stack.search(10);
System.out.println("10์ ์์น: " + position); // 2
}
}