ddubi

백준 10828 : 스택 (Java) 본문

코테 문제풀이

백준 10828 : 스택 (Java)

ddubi__ 2022. 10. 5. 21:23

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

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

시간이 없어서 직관적으로만 푼 문제.

나중에 더 재미있게 풀어봐야지.

 

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

public class back_10828 {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		
		Stack<Integer> list = new Stack<Integer>();
		for(int i=0; i<N; i++) {
			String[] reader = br.readLine().split(" ");
			String target = reader[0];
			if(target.equals("push")) {
				int num = Integer.parseInt(reader[1]);
				list.push(num);
			} else if(target.equals("top")) {
				if(list.isEmpty()) {
					System.out.println(-1);
				} else {
					System.out.println(list.peek());
				}
			} else if(target.equals("size")) {
				System.out.println(list.size());
			} else if(target.equals("empty")) {
				if(list.isEmpty()) {
					System.out.println(1);
				} else {
					System.out.println(0);
				}
			} else if(target.equals("pop")) {
				if(list.isEmpty()) {
					System.out.println(-1);
				} else {
					System.out.println(list.pop());
				}
			}
		}
	}
}
Comments