코딩 기록/자바스크립트
(JavaScript) 자바스크립트 큐(Queue, FIFO) 자료구조 구현
kimyang-Sun
2021. 2. 9. 00:41

자바스크립트로 큐(Queue) 기능을 구현해봤습니다.
큐는 FIFO로 First In First Out, 처음으로 들어온 데이터가 처음으로 나가는 구조입니다.
// 큐 클래스
class Queue {
constructor() {
this._size = 0; // 현재 데이터 수
this.head; // queue 기준 현재 값
this.tail; // queue 기준 가장 마지막 값
}
// 묶여있는 _size를 밖에서 호출해주기 위해 getter를 사용합니다.
get size() {
return this._size;
}
// 큐 추가
enQueue(value) {
const node = { value };
if (this._size === 0) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
this._size++;
}
// 큐 제거
deQueue() {
if (!this.head) throw new Error('queue not exist..😑'); // 큐가 하나도 없는 상태면 에러 발생
if (this.head.value === this.tail.value) {
this.tail = undefined;
}
const next = this.head.next;
this.head = next;
this._size--;
}
// 큐 검색 = index
search(num) {
// 큐가 하나도 없거나 해당하는 큐가 없을 경우에 에러 발생
if (!this.head) {
throw new Error('queue not exist..😑');
} else if (num < 0 || num >= this._size) {
throw new Error('No corresponding queues found..😣');
}
let count = 0;
let current = this.head;
while (num > count) {
current = current.next;
count++;
}
return current.value;
}
}
주요기능
- size : 현재 들어가있는 데이터의 수
- enQueue : 입력된 데이터를 추가하는 함수
- deQueue : 데이터를 제거하는 함수
- search : 입력된 숫자에 해당하는 데이터를 반환하는 함수 (배열의 index와 같습니다)
마지막으로 콘솔로 테스트 해보겠습니다.
const queue = new Queue(); // 클래스 생성
console.log(queue); // 초기 데이터
// 데이터 추가
queue.enQueue('google');
console.log(queue);
queue.enQueue('samsung');
console.log(queue);
queue.enQueue('lg');
console.log(queue);
// index 확인
console.log(queue.search(0), queue.search(1), queue.search(2));
// 데이터 제거
queue.deQueue();
console.log(queue);
queue.deQueue();
console.log(queue);
queue.deQueue();
console.log(queue);




밑에는 타입스크립트의 큐입니다.
(TypeScript) 타입스크립트 큐(Queue, FIFO) 자료구조 구현
타입스크립트로 큐(Queue) 기능을 구현해봤습니다. 큐는 FIFO로 First In First Out, 처음으로 들어온 데이터가 처음으로 나가는 구조입니다. // 큐 추상화 인터페이스 interface Queue { readonly size: number;..
kimyang-sun.tistory.com