알고리즘

[백준/Java] 10828 : 스택

Stitchhhh 2025. 2. 16. 22:29

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

 

입력값 중에서 4개는 하나의 단어로 이루어져있으므로 해당되면 다음 i로 넘어가도록 continue를 해놓고, 남은 한 가지의 경우에는 두 단어 이루어져있으므로 StringTokenizer로 받아서 문제를 풀이하였다.

 

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

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

		Stack<Integer> stack = new Stack<>();

		for (int i = 0; i < N; i++) {

			String str = br.readLine();

			if (str.equals("top")) {
				if (stack.isEmpty())
					System.out.println(-1);
				else
					System.out.println(stack.peek());
				continue;
			}
			if (str.equals("size")) {
				System.out.println(stack.size());
				continue;
			}
			if (str.equals("empty")) {
				if (!stack.isEmpty())
					System.out.println(0);
				else
					System.out.println(1);
				continue;
			}
			if (str.equals("pop")) {
				if (stack.isEmpty())
					System.out.println(-1);
				else
					System.out.println(stack.pop());
				continue;
			}
			StringTokenizer st = new StringTokenizer(str);

			str = st.nextToken();
			if (str.equals("push")) {
				stack.push(Integer.parseInt(st.nextToken()));
			}
		}		
        br.close();
	}
}