10866.
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
💻출력
2
1
2
0
2
1
-1
0
1
-1
0
3
📌풀이
216ms, 18588kb
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Deque_10866 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
Deque<Integer> deque = new LinkedList<>();
int n = Integer.parseInt(br.readLine());
for(int i = 0; i < n; i++){
st = new StringTokenizer(br.readLine());
String command = st.nextToken();
if(command.equals("push_front")){
int tmp = Integer.parseInt(st.nextToken());
deque.addFirst(tmp);
}
else if(command.equals("push_back")){
int tmp = Integer.parseInt(st.nextToken());
deque.addLast(tmp);
}
else if(command.equals("pop_front")){
int num = deque.isEmpty() ? -1 : deque.pollFirst();
sb.append(num).append("\n");
}
else if(command.equals("pop_back")){
int num = deque.isEmpty() ? -1 : deque.pollLast();
sb.append(num).append("\n");
}
else if(command.equals("size")){
sb.append(deque.size()).append("\n");
}
else if(command.equals("empty")){
int num = deque.isEmpty() ? 1 : 0;
sb.append(num).append("\n");
}
else if(command.equals("front")){
int num = deque.isEmpty() ? -1 : deque.peekFirst();
sb.append(num).append("\n");
}
else if(command.equals("back")){
int num = deque.isEmpty() ? -1 : deque.peekLast();
sb.append(num).append("\n");
}
}
System.out.print(sb);
}
}
자바에서 제공해주는 deque를 활용해서 풀었음
'Algorithm > PTUStudy' 카테고리의 다른 글
9주차. 스택,큐 (큐를 이용한 스택구현) (0) | 2023.03.30 |
---|---|
8주차. 단어 뒤집기 2 (0) | 2023.03.30 |
8주차. 스택, 큐(일일 온도) (0) | 2023.03.30 |
8주차. 스택,큐 (중복 문자 제거) (0) | 2023.03.30 |
8주차. 스택, 큐(유효한 괄호) (0) | 2023.03.30 |