๋ฌธ์
https://www.acmicpc.net/problem/10866
ํ์ด
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.*;
public class ๋ฑ {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
Deque<Integer> deque = new ArrayDeque<>();
for(int i=0; i<n; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
String s = st.nextToken();
switch(s){
case "push_front":
deque.addFirst(Integer.parseInt(st.nextToken()));
break;
case "push_back":
deque.addLast(Integer.parseInt(st.nextToken()));
break;
case "pop_front":
if(deque.isEmpty()) sb.append(-1).append("\n");
else sb.append(deque.pollFirst()).append("\n");
break;
case "pop_back":
if(deque.isEmpty()) sb.append(-1).append("\n");
else sb.append(deque.pollLast()).append("\n");
break;
case "size":
sb.append(deque.size()).append("\n");
break;
case "empty" :
if(deque.isEmpty()) sb.append(1).append("\n");
else sb.append(0).append("\n");
break;
case "front":
if(deque.isEmpty()) sb.append(-1).append("\n");
else sb.append(deque.peekFirst()).append("\n");
break;
case "back":
if(deque.isEmpty()) sb.append(-1).append("\n");
else sb.append(deque.peekLast()).append("\n");
break;
}
}
System.out.println(sb);
}
}
์๋ฐ์ Deque๋ฅผ ์ด์ฉํ์ฌ ํ์๋ค. ๋ฑ์ด ๋น์ด์์ ๋๋ฅผ ์ฃผ์ํ์ฌ ํด๊ฒฐํ๋ฉด ๋๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Java] [Silver2] 1874๋ฒ_์คํ ์์ด (0) | 2024.01.13 |
---|---|
๐ฉ [๋ฐฑ์ค] [Java] [Silver3] 1966๋ฒ_ํ๋ฆฐํฐ ํ (0) | 2024.01.12 |
๐ฉ [๋ฐฑ์ค] [Java] [Silver2] 1260๋ฒ_DFS์ BFS (0) | 2024.01.08 |
๐ฉ [๋ฐฑ์ค] [Java] [Silver5] 2941๋ฒ_ํฌ๋ก์ํฐ์ ์ํ๋ฒณ (0) | 2023.12.10 |
๐ฉ [๋ฐฑ์ค] [Java] [Silver5] 1316๋ฒ_๊ทธ๋ฃน ๋จ์ด ์ฒด์ปค (1) | 2023.12.08 |