10866번
문제
정수를 저장하는 덱(Deque)를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여덟 가지이다.
pushfront X: 정수 X를 덱의 앞에 넣는다.
pushback X: 정수 X를 덱의 뒤에 넣는다.
popfront: 덱의 가장 앞에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
popback: 덱의 가장 뒤에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
size: 덱에 들어있는 정수의 개수를 출력한다.
empty: 덱이 비어있으면 1을, 아니면 0을 출력한다.
front: 덱의 가장 앞에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
back: 덱의 가장 뒤에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
문제 해결 순서
- 배열로 deque 구현.
- 노드 클래스를 생성해 양방향 연결리스트로 구현.
- size를 기준으로 구현했지만 다른 방법이 있는지 찾아봐야할듯.
import java.util.Scanner;
public class Main {
static class Node{
Node next;
Node pre;
int n;
Node(int n){
this.next = null;
this.pre = null;
this.n = n;
}
}
public static Node deque;
public static Node head = deque;
public static Node tail = deque;
public static int[] stack;
public static int size = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int N = scan.nextInt();
stack = new int[N];
for(int i = 0; i < N; i++) {
String str = scan.next();
switch (str) {
case "push_front":
push_front(scan.nextInt());
break;
case "push_back":
push_back(scan.nextInt());
break;
case "pop_front":
sb.append(pop_front()).append('\n');
break;
case "pop_back":
sb.append(pop_back()).append('\n');
break;
case "size":
sb.append(size()).append('\n');
break;
case "empty":
sb.append(empty()).append('\n');
break;
case "front":
sb.append(front()).append('\n');
break;
case "back":
sb.append(back()).append('\n');
break;
}
}
System.out.println(sb);
}
static void push_front(int x){
Node temp = new Node(x);
if(size == 0){
head = temp;
tail = temp;
}
else{
temp.next = head;
head.pre = temp;
head = temp;
}
size++;
}
static void push_back(int x){
Node temp = new Node(x);
if(size == 0){
head = temp;
tail = temp;
}
else{
tail.next = temp;
temp.pre = tail;
tail = temp;
}
size++;
}
static int pop_front(){
if (size != 0){
int value = head.n;
head = head.next;
size--;
return value;
}
else
return -1;
}
static int pop_back(){
if (size != 0){
int value = tail.n;
tail = tail.pre;
size--;
return value;
}
else
return -1;
}
static int size(){
return size;
}
static int empty(){
if (size == 0){
return 1;
}
else{
return 0;
}
}
static int front(){
if(size != 0){
return head.n;
}
else
return -1;
}
static int back(){
if (size != 0){
return tail.n;
}
else
return -1;
}
}

