반응형


딱히 설명 할게 없을 것 같다. 자료구조 스택을 이용 하면 쉽게 답을 얻을 수 있다.

split으로 String과 int 부분을 나누는게 가장 어려운 듯 하다.


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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
 
public class Main {
 
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
 
        // Scanner sc = new Scanner(System.in);
        Scanner sc = new Scanner(new FileInputStream("input.txt"));
        int n = sc.nextInt();
        sc.nextLine();
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < n; i++) {
            String str = sc.nextLine();
 
            String instruction[] = str.split(" ");
 
            switch (instruction[0]) {
            case "push":
                stack.push(Integer.parseInt(instruction[1]));
                break;
 
            case "pop":
                if(stack.isEmpty()){
                    System.out.println(-1);
                }
                else{
                    System.out.println(stack.pop());
                }
                break;
 
            case "size":
 
                    System.out.println(stack.size());
                break;
 
            case "empty":
                if(stack.isEmpty()){
                    System.out.println(1);
                }
                else{
                    System.out.println(0);
                }
                break;
 
            case "top":
                if(stack.isEmpty()){
                    System.out.println(-1);
                }
                else{
                    System.out.println(stack.peek());
                }
                break;
 
            }
 
        }
 
    }
 
}
cs


반응형

+ Recent posts