정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여섯 가지이다.
첫째 줄에 주어지는 명령의 수 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
출력
1
2
2
0
1
2
-1
0
1
-1
0
3
LinkedList 사용: LinkedList queue = new LinkedList();
Iterator iter = list.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Queue {
static LinkedList<String> queue = new LinkedList<String>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String n;
int N = Integer.parseInt(br.readLine());
StringTokenizer split;
for(int i=0; i<N; i++) {
split = new StringTokenizer(br.readLine(), " ");
String str = split.nextToken();
if (str.equals("push")){
n = split.nextToken();
push(queue, n);
}
switch(str) {
case "pop":
sb.append(pop(queue)).append('\n');
break;
case "size":
sb.append(size(queue)).append('\n');
break;
case "empty":
sb.append(empty(queue)).append('\n');
break;
case "front":
sb.append(front(queue)).append('\n');
break;
case "back":
sb.append(back(queue)).append('\n');
break;
}
}
System.out.println(sb);
}
static void push(LinkedList<String> q, String str) {
q.add(str);
}
static String pop(LinkedList<String> q) {
// 큐가 비어있으면 -1
if (empty(q).equals("1")) {
return "-1";
}
return q.poll();
}
static String size(LinkedList<String> q) {
return Integer.toString(q.size());
}
static String empty(LinkedList<String> q) {
if(q.size()==0)
return "1";
return "0";
}
static String front(LinkedList<String> q) {
if (empty(q).equals("1")) {
return "-1";
}
return q.peek();
}
static String back(LinkedList<String> q) {
if (empty(q).equals("1")) {
return "-1";
}
return q.peekLast();
}