덱(Deque)
- 덱은 Double-ended Queue 의 약자이다
- 스택과 큐를 합친 자료구조여서 양 끝에서 데이터를 넣거나 추출할 수 있다.
class Deque {
constructor() {
this.arr = [];
this.head = 0;
this.tail = 0;
}
push_front(item) {
if (this.arr[0]) {
for (let i = this.arr.length; i > 0; i--) {
this.arr[i] = this.arr[i - 1];
}
}
this.arr[this.head] = item;
this.tail++;
}
push_back(item) {
this.arr[this.tail++] = item;
}
pop_front() {
if (this.head >= this.tail) {
return null;
} else {
const result = this.arr[this.head++];
return result;
}
}
pop_back() {
if (this.head >= this.tail) {
return null;
} else {
const result = this.arr[--this.tail];
return result;
}
}
}
let deque = new Deque();
deque.push_front(1);
deque.push_front(2);
console.log(deque.pop_front());
deque.push_front(3);
console.log(deque.pop_front());
console.log(deque.pop_front());
console.log(deque.pop_front());
deque.push_back(5);
console.log(deque.pop_back());
console.log(deque.pop_back());
deque.push_back(6);
deque.push_front(9);
감사합니다!