정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여섯 가지이다.
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)
이 주어진다. 둘째 줄부터 N
개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
-문제를 만든 사람: jh05013
import java.io.*;
import java.util.*;
public class Code18258 {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int N=Integer.valueOf(br.readLine());
Queue<Integer> queue=new LinkedList<>();
StringBuilder sb=new StringBuilder();
int last=0;
for(int i=0;i<N;i++){
String[] temp=br.readLine().split(" ");
if(temp[0].equals("push")){
queue.add(Integer.valueOf(temp[1]));
last=Integer.valueOf(temp[1]);
}
else{
if(temp[0].equals("pop")){
if(queue.isEmpty()){
sb.append("-1"+"\n");
continue;
}
else{
sb.append(String.valueOf(queue.poll())+"\n");
continue;
}
}
else if(temp[0].equals("size")){
sb.append(String.valueOf(queue.size())+"\n");
continue;
}
else if(temp[0].equals("empty")){
if(queue.isEmpty()){
sb.append("1"+"\n");
continue;
}
else{
sb.append("0"+"\n");
continue;
}
}
else if(temp[0].equals("front")){
if(queue.isEmpty()){
sb.append("-1"+"\n");
continue;
}
else{
sb.append(String.valueOf(queue.peek())+"\n");
continue;
}
}
else if(temp[0].equals("back")){
if(queue.isEmpty()){
sb.append("-1"+"\n");
continue;
}
else{
sb.append(String.valueOf(last)+"\n");
continue;
}
}
}
}
br.close();
System.out.println(sb);
}
}
velog 오류때문에 고찰이 다 초기화 돼서 다시 적으러 왔다..
back
부분 때문에 시간초과가 났었다. 그래서 push
할 때 last
변수를 이용해 최신 값을 저장해두었다.