본문 바로가기
Baekjoon

[백준] 10828- 스택 [JAVA]

by kssosoy 2025. 6. 16.

[정답]

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());
            }
        }



    }
}

[풀이]

스택 연습문제이기 때문에 문제에서 말해준 조건만 맞춰서 조건문을 사용해주고 출력하는 문제