https://www.acmicpc.net/problem/10828
자료구조, 스택
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static List stack = new ArrayList();
static StringTokenizer st;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfCase = Integer.parseInt(br.readLine());
for(int i=0; i<numOfCase; i++){
st = new StringTokenizer(br.readLine());
readCommand(st.nextToken());
}
}
public static void readCommand(String input){
if (input.equals("push")) {
int X = Integer.parseInt(st.nextToken());
push(X);
}
if (input.equals("pop")) {
pop();
}
if (input.equals("size")) {
size();
}
if (input.equals("empty")) {
empty();
}
if (input.equals("top")) {
top();
}
}
public static void push(int X){
stack.add(X);
}
public static void pop(){
if(stack.size() == 0){
System.out.println(-1);
} else{
System.out.println(stack.remove(stack.size()-1));
}
}
public static void size(){
System.out.println(stack.size());
}
public static void empty(){
if(stack.size() == 0){
System.out.println(1);
} else{
System.out.println(0);
}
}
public static void top(){
if(stack.size() == 0){
System.out.println(-1);
} else{
System.out.println(stack.get(stack.size()-1));
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
백준 9012번 - 괄호 (Java 8) (0) | 2022.03.08 |
---|---|
백준 9093번 - 단어 뒤집기 (Java 8) (0) | 2022.03.08 |
백준 2021번 - 등수 매기기 (Java 8) (0) | 2022.03.07 |
백준 15651번 - N과 M (3) (Java 8) (0) | 2022.03.07 |
백준 9663번 - N-Queen (Java 8) (0) | 2022.03.07 |
댓글