스택(stack)은 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조(LIFO - Last In First Out)으로 되어 있다. 자료를 넣는 것을 '밀어넣는다' 하여 푸쉬(push)라고 하고 반대로 넣어둔 자료를 꺼내는 것을 팝(pop)이라고 하는데, 이때 꺼내지는 자료는 가장 최근에 푸쉬한 자료부터 나오게 된다. 이처럼 나중에 넣은 값이 먼저 나오는 것을 LIFO 구조라고 한다.
Stack<Type> stacks = new Stack<>();
// Create Integer type stack
Stack<Integer> stacks = new Stack<>();
// Create String type stack
Stack<String> stacks = new Stack<>();
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Add elements to Stack
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
}
}
// Stack: [Dog, Horse, Cat]
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Add elements to Stack
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Initial Stack: " + animals);
// Remove element stacks
String element = animals.pop();
System.out.println("Removed Element: " + element);
}
}
// Initial Stack: [Dog, Horse, Cat]
// Removed Element: Cat
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Add elements to Stack
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
// Access element from the top
String element = animals.peek();
System.out.println("Element at top: " + element);
}
}
// Stack: [Dog, Horse, Cat]
// Element at top: Cat
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Add elements to Stack
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
// Search an element
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
}
}
// Stack: [Dog, Horse, Cat]
// Position of Horse: 2
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Add elements to Stack
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
// Check if stack is empty
boolean result = animals.empty();
System.out.println("Is the stack empty? " + result);
}
}
// Stack: [Dog, Horse, Cat]
// Is the stack empty? false