-
JS Queue자바스크립트/기본문법 2023. 8. 5. 22:30
const arr= []; const enqueue= (data)=>{ arr.push(data); }; const dequeue= ()=>{ return arr.shift(); }; enqueue(1); //arr= [1]; enqueue(2); //arr= [1,2] dequeue(); //arr= [2]
JS에선 기본 내장함수로 push, pop, shift를 제공하기에
간단하게 스택과 큐를 구현할 수 있다.
그래서 큐를 따로 제공해주질 않는다.class Queue { constructor() { this.storage = {}; this.front = 0; this.rear = 0; } size() { if (this.storage[this.rear] === undefined) { return 0; } else { return this.rear - this.rear + 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) { temp = this.storage[this.front]; delete this.storage[this.front]; this.front = 0; this.rear = 0; } else { temp = this.storage[this.front]; delete this.storage[this.front]; this.front += 1; } return temp; } }
[자료구조] JS로 구현하는 큐 (Queue)
미루고 미루던 자바스크립트로 큐를 구현해야하는 순간이 오고야 말았다. 알고리즘 문제를 풀다 보면 큐(Queue) 자료구조를 이용해서 문제를 해결하는 경우를 종종 만날 수 있다. 대표적으로 BFS
velog.io
클래스로 구현한 큐
export default class Queue { constructor() { this.storage = {}; this.front = 0; this.rear = 0; this.size = 0; } isEmpty(){ if(this.size==0){ return true; } else{ return false; } } push(value) { this.storage[this.rear++] = value; this.size++; } pop() { if(this.size==0){ console.log("큐가 비었습니다!"); } else{ this.size--; let temp = this.storage[this.front]; delete this.storage[this.front]; this.front++; if(this.front == this.rear){ this.front = 0; this.rear = 0; } return temp; } } values(){ return Object.values(this.storage); } fronts(){ return this.storage[this.front].pt; } }
내 식대로 조금 수정해본 큐
'자바스크립트 > 기본문법' 카테고리의 다른 글
Enum (열거형) (0) 2023.08.07 csv, json, xml 파일 데이터 읽기 (0) 2023.08.07 정규표현식 (0) 2023.08.03 async & await (0) 2023.07.29 Promise 객체 (0) 2023.07.24