문제
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
- push X: 정수 X를 스택에 넣는 연산이다.
- pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 스택에 들어있는 정수의 개수를 출력한다.
- empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
- top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
입력
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다.
주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다.
문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
해결 방법
- Stack의 구조를 참고
- 시간 제한이 0.5초이기 때문에 BufferedReader와 BufferedWriter를 사용
- BufferedReader의 readline()은 말 그대로 라인 한 줄을 읽어오는 것이기 때문에 " "(공백)으로 split 해주고 판단한다.
import java.io.*; public class Week02_10828 { public static class ArrayStack { private int top; private int[] array; public ArrayStack(int maxSize) { this.top = -1; this.array = new int[maxSize]; } public void push(int x) { array[++top] = x; } public int pop() { if (this.top == -1) return -1; else { int result = array[top]; top--; return result; } } public int empty() { if (this.top == -1) return 1; else return 0; } public int top() { if(this.top == -1) return -1; else return array[top]; } public int size() { return top + 1; } } public static void main(String[] args) throws IOException, NullPointerException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); ArrayStack as = new ArrayStack(n); for (int i = 0; i < n; i++) { String[] command = br.readLine().split(" "); switch (command[0]) { case "push": as.push(Integer.parseInt(command[1])); break; case "pop": bw.write(as.pop() + "\n"); break; case "top": bw.write(as.top() + "\n"); break; case "empty": bw.write(as.empty() + "\n"); break; case "size": bw.write(as.size() + "\n"); break; } bw.flush(); } bw.close(); } }
다른 사람의 더 좋은 코드
자바의 Stack 클래스를 사용하면 더 간결하게 구현 가능하다.
참고
'algorithm' 카테고리의 다른 글
| [BOJ] 1764. 듣보잡 (0) | 2022.10.21 |
|---|---|
| [BOJ] 17298. 오큰수 (0) | 2022.10.21 |
| [BOJ] 2309. 일곱 난쟁이 (0) | 2022.10.21 |
| [BOJ] 1620. 나는야 포켓몬 마스터 이다솜 (0) | 2022.10.21 |
| [BOJ] 1181. 단어 정렬 (0) | 2022.10.21 |