https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
저는 deque를 이용해 문제를 해결하였습니다.
deque를 통해 back인 경우 마지막을 peek해서 해결하였고, 나머지는 큐처럼 해결하였습니다.
package BOJ.etc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_10845 {
private static final int EMPTY = -1;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
Deque<Integer> q = new LinkedList<>();
for(int i = 0 ; i < n ; i++){
st = new StringTokenizer(br.readLine()," ");
String command = st.nextToken();
if("push".equals(command)){
int num = stoi.apply(st.nextToken());
q.offerLast(num);
continue;
}
if("pop".equals(command)){
if(q.isEmpty()){
System.out.println(EMPTY);
}else{
System.out.println(q.poll());
}
continue;
}
if("size".equals(command)){
System.out.println(q.size());
continue;
}
if("empty".equals(command)){
if(q.isEmpty()){
System.out.println(1);
}else{
System.out.println(0);
}
continue;
}
if("front".equals(command)){
if(q.isEmpty()){
System.out.println(EMPTY);
}else{
System.out.println(q.peek());
}
continue;
}
if("back".equals(command)){
if(q.isEmpty()){
System.out.println(EMPTY);
}else{
System.out.println(q.peekLast());
}
continue;
}
}
}
}
'알고리즘' 카테고리의 다른 글
백준 21278번 호석이 두마리 치킨 (JAVA) (0) | 2023.09.25 |
---|---|
백준 1052번 물병 (JAVA) (0) | 2023.09.24 |
프로그래머스 수 조작하기 (JAVA) (0) | 2023.09.22 |
백준 1124번 언더프라임 (JAVA) (0) | 2023.09.21 |
백준 1138번 한 줄로 서기 (JAVA) (0) | 2023.09.20 |