[JAVA] Stack 사용하기
- java.util 패키지의 Collection 프레임워크
- 후입선출(LIFO : Last In First Out)
🔩 선언
Stack<String> stringStack = new Stack<String>(); // String타입
Stack<Character> charStack = new Stack<Character>(); // Char타입
Stack<Integer> integerStack = new Stack<Integer>(); // Integer타입
Stack<Integer> integerStack2 = new Stack<>(); // 뒷 부분 타입 생략 가능
Integer, String, Character 등 다양한 형타입으로 선언 가능
Stack stack = new Stack(); // 타입 선언 생략 가능 > Object로 선언
Stack<class> stack = new Stack<class>(); // class타입
형타입 생략 가능하지만 웬만하면 명시해주는걸로..!
🔩 Stack 값 추가 : push()
stack.push(5);
stack.push(6);
🔩 Stack 값 제거 : pop();
stack.pop(); //6 제거
stack.pop(); //5 제거
*값이 없는데 pop()을 하면 오류가 떨어지기 때문에 널체크 주의!
🔩 Stack 크기 구하기 : size();
stack.size()
🔩 Stack 값 구하기 : peek();
import java.util.*;
import java.io.*;
public class StackDemo {
// Main Method
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use push() to add elements into the Stack
stack.push("Welcome");
stack.push("To");
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");
// Displaying the Stack
System.out.println("Stack: " + stack);
// Fetching the element at the head of the Stack
System.out.println("The element at the top of the"+ " stack is: " + stack.peek());
}
}
> 결과
Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
🔩 Stack 값 비우기 : clear();
🔩 Stack null 체크 : isEmpty();
ref. https://www.geeksforgeeks.org/stack-class-in-java/
Stack Class in Java - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
🗒 간단한 Stack 문제 풀고 싶으면 아래 문제 추천
https://www.acmicpc.net/problem/9012
9012번: 괄호
괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고
www.acmicpc.net