https://www.acmicpc.net/problem/10866
- 예제 입력1
15
push_back 1
push_front 2
front
back
size
empty
pop_front
pop_back
pop_front
size
empty
pop_back
push_front 3
empty
front
- 예제 출력1
2
1
2
0
2
1
-1
0
1
-1
0
3
- 예제 입력2
22
front
back
pop_front
pop_back
push_front 1
front
pop_back
push_back 2
back
pop_front
push_front 10
push_front 333
front
back
pop_back
pop_back
push_back 20
push_back 1234
front
back
pop_back
pop_back
- 예제 출력2
-1
-1
-1
-1
1
1
2
2
333
10
10
333
20
1234
1234
20
- 문제 접근
- Deque(Double Ended Queue) 사용 문제
- push ⇒ offer 명령어 / add = 예외 발생
- pop ⇒ poll 명령어 / remove = 예외 발생
- front, back ⇒ peek명령어 / get = 예외 발생
- 출력 ⇒ 출력할 정수가 없으면 -1 → null일 경우 -1 출력
- 문제 해결
- 명령어 수를 입력 받음
- switch-case문으로 8개의 명령문을 구현
- 기존 풀이
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
Deque<Integer> deque = new LinkedList<>();
int CommandCnt = Integer.parseInt(br.readLine());
for(int i = 0; i < CommandCnt; i++){
Integer output = -999; // 출력할 결과가 -999일 떄 출력하지 않음
String[] input = br.readLine().split(" ");
String command = input[0];
switch(command){
case "push_front" : deque.offerFirst(Integer.parseInt(input[1])); break;
case "push_back" : deque.offerLast(Integer.parseInt(input[1])); break;
case "pop_front" : output = deque.pollFirst(); break;
case "pop_back" : output = deque.pollLast();break;
case "front" : output = deque.peekFirst();break;
case "back" : output = deque.peekLast(); break;
case "size" : output = deque.size(); break;
case "empty" : output = deque.isEmpty() ? 1 : 0; break;
}
// Deque가 비어있을 때 poll 또는 peek을 하면 null
if(output == null) output = -1;
// output이 -999라면(add, offer 됐다면) 출력하지 않음
if(output != -999) sb.append(output).append("\n");
}
System.out.println(sb);
}
'Coding Test > Problem Number' 카테고리의 다른 글
[Java] N과 M 2 [15650번] (0) | 2024.07.22 |
---|---|
[Java] N과 M 1 [15649번] (0) | 2024.07.21 |
[Java] 숫자 카드 2 [10816번] (0) | 2024.07.20 |
[Java] 숫자 카드 [10815번] (0) | 2024.07.20 |
[Java] 가희와 키워드 [22233번] (0) | 2024.07.20 |