큐
- 한쪽 끝으로 자료를 넣고, 반대쪽에서는 자료를 뺄 수 있는 선형구조.[컴퓨터인터넷IT용어대사전]
- Ex) 양쪽 구멍이 뚫린 파이프 => 한쪽 끝에서 무언가를 밀어 넣으면 반대쪽 끝에서 나옴
- FIFO(First In First Out) 자료 구조
- 순서대로 처리되어야 하는 일에 사용 될 수 있다
큐의 메소드
- enqueue: 큐의 가장 마지막에 데이터를 추가하는 메소드
- dequeue: 큐의 가장 앞의 데이터를 추출하는 메소드
- peek: 맨 앞의 데이터를 보여주는 메소드(데이터를 추출하진 않는다)
- isEmpty: 큐의 원소 존재 유무를 반환해주는 메소드
코드 구현 => 연결리스트(Linked List)를 이용한 구현
// 큐를 연결할 Node 클래스
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// 큐(Queue)의 구현
class Queue {
cunstructor() {
this.head = null;
this.tail = null;
}
enqueue(data) {
const needToAdd = new Node(data);
if (this.isEmpty()) {
this.head = needToAdd;
this.tail = needToAdd;
return;
}
this.tail.next = needToAdd;
this.tail = needToAdd;
return;
}
dequeue() {
if (this.isEmpty()) {
console.log("Queue is empty!");
return;
}
const tempNode = this.head.next;
this.head = tempNode;
return;
}
peek() {
if (this.isEmpty()) {
console.log("Queue is empty!");
return;
}
const data = this.head.data;
return data;
}
isEmpty() {
if (this.head == null) {
return true;
} else {
return false;
}
}
}