#유형 : 스택

#난이도 : 실버 4

# 스택의 기본 문제, 명령 종류와 조건에 따라 구현하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package bj;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
 
public class p10828 {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        Stack<Integer> stack = new Stack<>();
        for(int i=0; i<N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            String cmd = st.nextToken();
            if(cmd.equals("push")) {
                int val = Integer.parseInt(st.nextToken());
                stack.push(val);
            }else if(cmd.equals("pop")) {
                if(stack.isEmpty())
                    System.out.println(-1);
                else
                    System.out.println(stack.pop());
            }else if(cmd.equals("size")) {
                System.out.println(stack.size());
            }else if(cmd.equals("empty")) {
                if(stack.isEmpty())
                    System.out.println(1);
                else
                    System.out.println(0);
            }else {
                if(stack.isEmpty())
                    System.out.println(-1);
                else
                    System.out.println(stack.peek());
            }
        }
    }
}
 
cs

'백준' 카테고리의 다른 글

#백준_1038 괄호 - Java 자바  (0) 2021.11.21
#백준_9012 괄호 - Java 자바  (0) 2020.07.06
#백준_1629 곱셈 - Java 자바  (0) 2020.07.01
#백준_2096 내려가기 - Java 자바  (0) 2020.06.27
#백준_2473 세 용액 - Java 자바  (0) 2020.05.11

+ Recent posts