Computer Science/알고리즘

백준 Java | BOJ 10828 스택

토마토. 2023. 2. 1. 14:52
package DAY03.P10828;

import jdk.internal.util.xml.impl.Input;

import java.io.*;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static int N;
    public static Stack<Integer> stack;
    public static void main(String[] args) throws IOException {
        System.setIn(new FileInputStream("src/DAY03/P10828/input.txt"));
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(bf.readLine());
        stack = new Stack<>();
        // bf.readLine();
        for (int i=0;i<N;i++){
            String command = bf.readLine();
            if (command.equals("top")){
                if (stack.empty()){
                    System.out.println(-1);
                } else {
                    System.out.println(stack.peek());
                }
            } else if (command.equals("size")){
                System.out.println(stack.size());
            } else if (command.equals("empty")){
                boolean result = stack.empty();
                if (result){
                    System.out.println(1);
                } else {
                    System.out.println(0);
                }
            } else if (command.equals("pop")) {
                if (stack.empty()){
                    System.out.println(-1);
                } else {
                    System.out.println(stack.pop());
                }
            } else {
                // split by " "
                String[] command_with_param = command.split(" ");
                String command_str = command_with_param[0];
                int param = Integer.parseInt(command_with_param[1]);
                stack.push(param);
            }
        }
    }
}