정수를 저장하는 덱을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여덟 가지이다.
1 X: 정수 X를 덱의 앞에 넣는다. (1 ≤ X ≤ 100,000)
2 X: 정수 X를 덱의 뒤에 넣는다. (1 ≤ X ≤ 100,000)
3: 덱에 정수가 있다면 맨 앞의 정수를 빼고 출력한다. 없다면 -1을 대신 출력한다.
4: 덱에 정수가 있다면 맨 뒤의 정수를 빼고 출력한다. 없다면 -1을 대신 출력한다.
5: 덱에 들어있는 정수의 개수를 출력한다.
6: 덱이 비어있으면 1, 아니면 0을 출력한다.
7: 덱에 정수가 있다면 맨 앞의 정수를 출력한다. 없다면 -1을 대신 출력한다.
8: 덱에 정수가 있다면 맨 뒤의 정수를 출력한다. 없다면 -1을 대신 출력한다.
첫째 줄에 명령의 수 N이 주어진다. (1 ≤ N ≤ 1,000,000)
둘째 줄부터 N개 줄에 명령이 하나씩 주어진다.
출력을 요구하는 명령은 하나 이상 주어진다.
출력을 요구하는 명령이 주어질 때마다 명령의 결과를 한 줄에 하나씩 출력한다.
예제 입력 1
11
6
1 3
1 8
7
8
3
2 5
1 2
5
4
4
예제 출력 1
1
8
3
8
3
5
3
class Node {
next = undefined
prev = undefined
constructor(val) {
this.value = val
}
}
class Deque {
head = undefined
tail = undefined
size = 0
insert(val, type) {
const curNode = new Node(val)
if(!this.size) {
if(!this.head) this.head = curNode
if(!this.tail) this.tail = curNode
} else {
if(type === 'front') {
this.head.prev = curNode
curNode.next = this.head
this.head = curNode
} else if(type === 'back') {
this.tail.next = curNode
curNode.prev = this.tail
this.tail = curNode
}
}
this.size += 1
}
frontExtract() {
if(!this.head) return -1
const curVal = this.head.value
this.head = this.head.next
if(!this.head) this.tail = undefined
else {
this.head.prev = undefined
}
this.size -= 1
return curVal
}
backExtract() {
if(!this.tail) return -1
const curVal = this.tail.value
this.tail = this.tail.prev
if(!this.tail) this.head = undefined
else {
this.tail.next = undefined
}
this.size -= 1
return curVal
}
length() {
return this.size
}
isEmpty() {
return !this.size ? 1 : 0
}
printFront() {
if(!this.head) return -1
return this.head.value
}
printBack() {
if(!this.tail) return -1
return this.tail.value
}
}
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split("\n")
const deque = new Deque()
const result = []
input.shift()
input.forEach(command => {
const [type, val] = command.split(" ")
switch(type) {
case '1':
deque.insert(Number(val), 'front')
break
case '2':
deque.insert(Number(val), 'back')
break
case '3':
result.push(deque.frontExtract())
break
case '4':
result.push(deque.backExtract())
break
case '5':
result.push(deque.length())
break
case '6':
result.push(deque.isEmpty())
break
case '7':
result.push(deque.printFront())
break
case '8':
result.push(deque.printBack())
break
default:
break
}
})
console.log(result.join("\n"))
Chobby님 혹시 이 덱 문제 풀다가 모르는게 있는데,
왜 틀렸는지 한번 봐주실 수 있으실까요?
52퍼 정도 되니까 끊기네요...