코딩테스트에서 큐 구현할 경우 라이브러리처럼 사용
class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
//삽입
enqueue(item) {
this.items[this.tailIndex] = item;
this.tailIndex++;
}
//삭제
dequeue() {
const item = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return item;
}
//맨 앞에 있는거 꺼내기
peek() {
return this.items[this.headIndex];
}
//길이 구하기
getLength() {
return this.tailIndex - this.headIndex;
}
//전체 아이템 반환
getItems() {
return this.items;
}
}
const queue = new Queue();
queue.enqueue(5);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(7);
queue.dequeue();
queue.enqueue(1);
queue.enqueue(4);
console.log("큐객체", queue);
console.log("꼭대기", queue.peek());
console.log("총개수", queue.getLength());
console.log("전체 아이템", queue.getItems());
while (queue.getLength() != 0) {
console.log(queue.dequeue());
}
'코테풀이 > 자바스크립트 코테 전환' 카테고리의 다른 글
자바스크립트 코딩테스트 정리 (0) | 2023.04.16 |
---|---|
[자바스크립트 | 프로그래머스 1단계] 정수 내림차순으로 배치하기, 자연수 뒤집어 배열로 만들기 (0) | 2022.08.07 |
[자바스크립트 | 프로그래머스 1단계] 가장 작은수 제거하기 (0) | 2022.08.07 |
[자바스크립트 | 프로그래머스 1단계] 평균구하기 (0) | 2022.08.06 |
[자바스크립트 | 프로그래머스 1단계] 하샤드 수 (0) | 2022.08.06 |
자바스크립트 큐 구현하기