백준 10828 스택

솜솜이·2023년 4월 10일
0

백준 알고리즘

목록 보기
10/10

백준 기초부터 다시 풀어보자

https://www.acmicpc.net/problem/10828

import sys
input = sys.stdin.readline

n = int(input())
arr = []
for i in range(n):
    tem = list(map(str, input().split()))
    
    if tem[0] == "push":
        arr.append(tem[1])
    
    elif tem[0] == "pop":
        if len(arr) == 0:
            print(-1)
        else:
            print(arr.pop())
    elif tem[0] == "size":
        print(len(arr))
    elif tem[0] == "empty":
        if len(arr) == 0:
            print(1)
        else:
            print(0)
    else:
        if len(arr) == 0:
            print(-1)
        else:
            print(arr[-1])

자바 코드

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

public class Main {

    static Stack<Integer> stack = new Stack<>();
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        for (int i = 0; i < n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            String s = st.nextToken();

            if (s.equals("push")) {
                stack.push(Integer.parseInt(st.nextToken()));
            }
            else if (s.equals("pop")) {
                if (stack.isEmpty()) {
                    System.out.println(-1);
                } else {
                    System.out.println(stack.pop());
                }
            }
            else if (s.equals("size")) {
                System.out.println(stack.size());
            }
            else if (s.equals("empty")) {
                if (stack.isEmpty()) {
                    System.out.println(1);
                } else {
                    System.out.println(0);
                }
            }
            else {
                if (stack.isEmpty()) {
                    System.out.println(-1);
                } else {
                    System.out.println(stack.peek());
                }
            }
        }
    }
}

자바로는 풀지 못했다...

0개의 댓글