문제링크 : https://www.acmicpc.net/problem/10828
문제풀이
Stack 자료구조를 이용해서 명령에 따라 그에 해당하는 작업을 처리하면 된다.
소스코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Stack;
import java.util.StringTokenizer;
public class p_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> stack = new Stack<Integer>();
while (N-- > 0) {
String command = br.readLine();
StringTokenizer st = new StringTokenizer(command);
switch (st.nextToken()) {
case "push":
stack.push(Integer.parseInt(st.nextToken()));
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;
}
}
br.close();
}
}
'Algorithm > 문제풀이' 카테고리의 다른 글
| [LeetCode] 1번: Two Sum (0) | 2019.06.28 |
|---|---|
| [백준] 4963번: 섬의 개수 (0) | 2019.06.28 |
| [백준] 1012번: 유기농 배추 (0) | 2019.06.21 |
| [백준] 2667번: 단지번호붙이기 (0) | 2019.06.21 |
| [백준] 7576번: 토마토 (0) | 2019.06.20 |