알고리즘 풀이/백준

[백준][Java] 10828번 스택

배게 2018. 5. 6. 05:40
728x90

스택 공부하는 느낌으로다가 풀이해주시면 됩니다.

stack클래스가 java library에 들어 있고

문제에서 요구하는 push, pop, size, empty, top을

객체적인 개념을 익힌 후에

풀면 어려운 것이 아님.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;
import java.util.Stack;

public class Main {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int N = sc.nextInt();
		Stack<Integer> stack = new Stack<Integer>();
		sc.nextLine();
		for(int i=0; i<N; i++) {
			String input = sc.nextLine();
			String[] instruction = input.split(" ");
			
			switch (instruction[0]) {
			case "push":
				stack.push(Integer.parseInt(instruction[1]));
				break;
			case "pop":
				if(stack.isEmpty()) System.out.println(-1);
				else System.out.println(stack.pop());
				break;
			case "size":
				System.out.println(stack.size());
				break;
			case "empty":
				if(stack.isEmpty()) System.out.println(1);
				else System.out.println(0);
				break;
			case "top":
				if(stack.isEmpty()) System.out.println(-1);
				else System.out.println(stack.peek()); 
				break;
			default:
				break;
			}
		}
	}
	
}