[정답]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Stack<Integer> stack = new Stack<Integer>();
for(int i=0; i<n; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
String command = st.nextToken();
if(command.equals("push")){
int x = Integer.parseInt(st.nextToken());
stack.push(x);
}
else if(command.equals("pop")){
if(stack.isEmpty()){
System.out.println("-1");
}else{
System.out.println(stack.pop());
}
}
else if(command.equals("top")){
if(stack.isEmpty()){
System.out.println(-1);
}
else{
System.out.println(stack.peek());
}
}
else if(command.equals("empty")){
if(stack.empty()){
System.out.println(1);
}
else{
System.out.println(0);
}
}
else if(command.equals("size")){
System.out.println(stack.size());
}
}
}
}
[풀이]
스택 연습문제이기 때문에 문제에서 말해준 조건만 맞춰서 조건문을 사용해주고 출력하는 문제
'Baekjoon' 카테고리의 다른 글
[백준] 2563- 색종이 [JAVA] (0) | 2025.06.18 |
---|---|
[백준]10773-제로(java) (0) | 2025.06.18 |
[백준] 4673 - 셀프 넘버 [JAVA] (0) | 2025.06.16 |
[백준] 2941- 크로아티아 알파벳 [JAVA] (0) | 2025.06.16 |
[백준] 1316- 그룹 단어 체커 [JAVA] (0) | 2025.06.16 |