본문 바로가기
알고리즘/구현

[백준 풀이_Java] 73659024 스택 (실버4)

by happyhelen 2024. 2. 19.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;

public class Main {

    static int N;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        String[] input;
        Stack<String> stack = new Stack<>();
        for(int i=0; i<N; i++){
            input = br.readLine().split(" ");
            String verb = input[0];
            switch (verb){
                case "push" :
                    stack.push(input[1]);
                    break;

                case "top":
                    if(!stack.isEmpty()){
                        String top = stack.peek();
                        System.out.println(top);
                    }else{
                        System.out.println("-1");
                    }
                    break;

                case "size":
                    int size = stack.size();
                    System.out.println(size);
                    break;

                case "empty":
                    if(stack.empty()){
                        System.out.println("1");
                    }else{
                        System.out.println("0");
                    }
                    break;

                case "pop":
                    if (!stack.isEmpty()) {
                        System.out.println(stack.pop());
                    } else {
                        System.out.println("-1");
                    }
                    break;
            }
        }

    }

}

 

 

 

'알고리즘 > 구현' 카테고리의 다른 글

[백준 풀이_Java] 14502 연구소 (골드4)  (0) 2024.02.19