ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준 10828] - [스택] - 스택 (JAVA)
    알고리즘/스택(Stack) 2018. 11. 30. 12:30

    문제 링크 : https://www.acmicpc.net/problem/10828




    이 문제는 별로 쓸 글은 없다.

    단순히 스택이 어떻게 돌아가는지 이해하는 문제여서 소스만 이쁘게 작성하면 된다. 



    소스


    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
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Stack;
    import java.util.StringTokenizer;
     
    public class Main {
        public static int size;
        public static Stack<Integer> stack;
        
        public static void main(String[] args) throws IOException{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = null;
            stack = new Stack<Integer>();
            
            size = Integer.parseInt(br.readLine());
            
            StringBuilder sb = new StringBuilder();
            for(int i=0; i < size; i++) {
                st = new StringTokenizer(br.readLine());
                
                String type = st.nextToken();
                if("push".equals(type)) {
                    int num = Integer.parseInt(st.nextToken());
                    stack.push(num);
                }else if("top".equals(type)) {
                    sb.append((stack.size() == 0)?-1+"\n":stack.peek() + "\n");
                }else if("pop".equals(type)) {
                    sb.append((stack.size() == 0)?-1+"\n":stack.pop() + "\n");
                }else if("size".equals(type)) {
                    sb.append(stack.size()+"\n");
                }else if("empty".equals(type)) {
                    sb.append((stack.isEmpty())?1+"\n":0 + "\n");
                }
            }
            System.out.println(sb.toString());
        }
    }
     
    cs


    댓글

Designed by Tistory.