백준 - JAVA/스택

[백준] 10828번 스택 _ JAVA ( 주석 설명 )

wch_s 2023. 3. 9. 18:57

풀이

1) 스택 Stack<Integer> stack = new Stack<>(); 을 만든다.

2) 각 명령마다 if 조건문을 만들어 처리를 해준다.

 

코드

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 void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        int N = Integer.parseInt(br.readLine()); //명령의 수

        Stack<Integer> stack = new Stack<>();
        for(int i=0;i<N;++i){
            st  = new StringTokenizer(br.readLine());
            String command = st.nextToken();

            if(command.equals("pop")){ //pop 명령
                if(stack.empty())
                    System.out.println(-1);
                else
                    System.out.println(stack.pop());
            }

            else if(command.equals("size")){ //size 명령
                System.out.println(stack.size());
            }

            else if(command.equals("empty")){ //empty 명령
                if(stack.empty())
                    System.out.println(1);
                else
                    System.out.println(0);
            }

            else if(command.equals("top")){ //top 명령
                if(stack.empty())
                    System.out.println(-1);
                else
                    System.out.println(stack.peek());
            }
            else{ //push 명령
                int push_num = Integer.parseInt(st.nextToken()); 
                stack.push(push_num);
            }
        }
    }
}