[백준] 28278 스택2

서은경·2023년 9월 11일
0

CodingTest

목록 보기
70/71
package baekjoon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main28278 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        StringBuilder sb = new StringBuilder();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < N; i++) {
            String command = br.readLine();
            if(command.startsWith("1")) {
                int x = Integer.parseInt(command.split(" ")[1]);
                stack.push(x);
            } else if(command.equals("2")) {
                if(stack.isEmpty()) {
                    sb.append("-1\n");
                } else {
                    sb.append(stack.pop()+"\n");
                    //stack.stream().map(num -> sb.append(num+"\n"));
                }
            } else if(command.equals("3")) {
                sb.append(stack.size()+"\n");
            } else if(command.equals("4")) {
                sb.append(stack.isEmpty() ? "1\n" : "0\n");
            } else if(command.equals("5")) {
                sb.append(stack.isEmpty() ? "-1\n" : stack.peek()+"\n");
            }
        }
        System.out.println(sb.toString());
    }
}

풀기만 하다가 오랜만에 포스팅..
문제 이해를 잘해야 된다!
2번이 맨 위 정수를 빼고 출력한다 였는데
나는 맨위를 pop으로 빼고 stack을 map으로 돌려서 쭉 처리해줬는데
그냥 pop한 정수를 출력하면 되는거였다
..그냥 포스팅하고 시펑서 가져왔다

0개의 댓글

관련 채용 정보