코테 문제를 풀다 보니 새로운 방법을 알게 되어 바로 기록합니다.
지난 Deque 코드는 여기서 확인할 수 있습니다 → [자료구조] Deque with JS 메모리 누수 방지
이름은 한 칸 비워두기 기법!!
지난 코드와 차이점은 size 변수를 활용했던 부분을 head와 tail을 활용해 해결할 수 있게 되었습니다. 처음에 원했던 방식으로 개인적으로 이 방식이 마음에 듭니다.
큰 변화는 없기 때문에 지난 코드와 비교해서 원하는 걸로 사용하면 될 것 같습니다.
class Deque {
#deque;
#capacity = 0;
#head = 0;
#tail = 0; // 한 칸 비워두기 시 0
// size 변수 삭제
constructor(capacity) {
this.#capacity = capacity + 1; // 한 칸 여유 공간 생성
this.#deque = new Array(capacity + 1);
}
isEmpty() {
return this.#head === this.#tail;
}
// capacity가 +1 되기 때문에 full 상태를 확인
isFull() {
return this.#head === (this.#tail + 1) % this.#capacity;
}
size() {
return (this.#tail - this.#head + this.#capacity) % this.#capacity;
}
pushFront(x) {
if (this.isFull()) return;
this.#head = (this.#head - 1 + this.#capacity) % this.#capacity;
this.#deque[this.#head] = x;
}
pushBack(x) {
if (this.isFull()) return;
this.#deque[this.#tail] = x;
this.#tail = (this.#tail + 1) % this.#capacity;
}
popFront() {
if (this.isEmpty()) return null;
const data = this.#deque[this.#head];
this.#head = (this.#head + 1) % this.#capacity;
return data;
}
popBack() {
if (this.isEmpty()) return null;
const data = this.#deque[this.#tail];
this.#tail = (this.#tail - 1 + this.#capacity) % this.#capacity;
return data;
}
print() {
let ret = [];
for (let i = this.#head; i < this.#head + this.size(); i++) {
ret.push(this.#deque[i % this.#capacity]);
}
console.log(ret.join(" "));
}
}
'알고리즘&코테' 카테고리의 다른 글
| [코테 꿀팁] JS 입력값 받아올 때 주의할 점 require('fs') (0) | 2025.06.13 |
|---|---|
| [자료구조 활용] Deque 이렇게도 활용할 수 있다! (0) | 2025.05.22 |
| [자료구조] Deque with JS 메모리 누수 방지 (0) | 2025.05.16 |
| [자료구조] Deque with JS 리팩토링 (0) | 2025.05.15 |
| [자료구조/미완] Linked List(연결리스트) with JS (0) | 2025.05.14 |