티스토리 뷰
참고자료: https://velog.io/@longroadhome/자료구조-JS로-구현하는-.큐-Queue
[자료구조] JS로 구현하는 큐 (Queue)
미루고 미루던 자바스크립트로 큐를 구현해야하는 순간이 오고야 말았다. 알고리즘 문제를 풀다 보면 큐(Queue) 자료구조를 이용해서 문제를 해결하는 경우를 종종 만날 수 있다. 대표적으로 BFS
velog.io
코드
<script>
class Queue {
constructor() {
this.storage = {}; //값을 저장할 객체
this.front = 0; // 첫 원소를 가리킬 포인터
this.rear = 0; // 마지막 원소를 가리킬 포인터
}
//크기 구하기
size() {
if (this.storage[rear] === undefined) return 0; // rear가 가리키는 값이 없을 때가 아무 데이터가 없는 경우이다
else return this.rear - this.front + 1;
}
add(value) {
if (this.size === 0) this.storage['0'] = value; //큐에 데이터가 없는 경우
else {
this.rear += 1;
this.storage[this.rear] = value;
}
}
popleft() {
let temp; // 첫 원소 값을 임시로 담을 변수
if (this.front === this.rear) { //데이터가 1개 있는 경우
temp = this.storage[this.front];
delete this.storage[this.front];
this.front = 0;
this.rear = 0;
} else { // 데이터가 2개 이상인 경우
temp = this.storage[this.front];
delete this.storage[this.front];
this.front += 1;
}
return temp;
}
}
</script>'ALGORITHM > Theory' 카테고리의 다른 글
| 재귀 기본 문제 (0) | 2022.04.22 |
|---|---|
| 재귀(Recursion) (0) | 2022.04.22 |
| Frequency Counter, Multiple Pointers, Sliding Window (0) | 2022.04.01 |
| 성능 평가, 문제 해결 접근법/패턴 (0) | 2022.03.31 |
| 빅오 표기법 (big O Notation) (0) | 2022.03.30 |
댓글