예제 입력
15 push 1 push 2 front back size empty pop pop pop size empty pop push 3 empty front
예제 출력
1 2 2 0 1 2 -1 0 1 -1 0 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.io.*; | |
/** | |
* https://www.acmicpc.net/problem/10845 | |
* BOJ 백준온라인져지 10845 큐 풀이 | |
*/ | |
class Main { | |
public static void main(String[] args) throws IOException{ | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); | |
Queue<Integer> queue = new LinkedList<>(); | |
int N = Integer.parseInt(br.readLine()); | |
while(N-- > 0){ | |
String str1[] = br.readLine().split(" "); | |
String temp = str1[0]; | |
if(temp.equals("push")){ | |
int number = Integer.parseInt(str1[1]); | |
queue.offer(number); | |
}else if(temp.equals("pop")){ | |
if(!isEmpty(queue, bw)){ | |
bw.write(queue.poll() + "\n"); | |
} | |
}else if(temp.equals("size")){ | |
bw.write(queue.size() + "\n"); | |
}else if(temp.equals("empty")){ | |
bw.write((queue.isEmpty() ? 1 : 0) + "\n"); | |
}else if(temp.equals("back")){ | |
if(!isEmpty(queue, bw)){ | |
Iterator<Integer> it = queue.iterator(); | |
int tempInteger = 0; | |
while(it.hasNext()) tempInteger = it.next(); | |
bw.write(tempInteger + "\n"); | |
} | |
}else if(temp.equals("front")){ | |
if(!isEmpty(queue, bw)){ | |
bw.write(queue.peek() + "\n"); | |
} | |
} | |
} | |
bw.flush(); | |
} | |
private static boolean isEmpty(Queue<Integer> queue, BufferedWriter bw) throws IOException{ | |
if(queue.isEmpty()){ | |
bw.write("-1\n"); | |
} | |
return queue.isEmpty(); | |
} | |
} |
front는 맨 처음에 offer된 변수를 출력하면 된다.
Java에서는 front같은 메소드가 없는거 같아서 iterator에서를
돌려서 출력해줬다.
'IT > 알고리즘' 카테고리의 다른 글
BOJ 백준온라인져지 1002 터렛 풀이 (0) | 2017.11.30 |
---|---|
BOJ 백준온라인져지 11866 조세퍼스 문제 0 풀이 (0) | 2017.11.29 |
BOJ 백준온라인져지 2504 괄호의 값 풀이 (0) | 2017.11.28 |
BOJ 백준온라인져지 1874 스택 수열 풀이 (0) | 2017.11.27 |
BOJ 백준온라인져지 9020 골드바흐의 추측 풀이 (0) | 2017.11.25 |