JS에서 큐 작성(연결 목록 사용)
먼저 연결 목록을 구현합니다.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// add node to the linked list
add(element) {
// creates node
const newNode = new Node(element);
// if list is empty, set node to be the head
if (this.size === 0) {
this.head = newNode;
} else {
// otherwise, loop until we find last node, and we set next to be the new node
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// increase size
this.size++;
}
// remove node that contains a certain elements
removeElement(element) {
// set current to head
let current = this.head;
// if current.data === element, set next as head and return
if (current.data === element) {
this.head = current.next;
console.log(`${element} removed`);
this.size--;
return;
// otherwise
} else {
// loop the linked list until the end (while current.next is not null)
while (current.next) {
// if we find a node with the data we are looking for
if (current.next.data === element) {
// if it is, set the next node of current as the next of the one we want to remove (current.next.next)
current.next = current.next.next;
console.log(`${element} removed`);
// decrease size of the linked list
this.size--;
return;
} else {
// otherwise, set current to be current.next so we can continue the loop
current = current.next;
}
}
// print "not found" and return
console.log(`${element} not found`);
return;
}
}
removeHead() {
// store head's next in a temp variable
const temp = this.head.next;
// we set the tem as head, so the old head is gone
this.head = temp;
// reduce size as the LL is one element less
this.size--;
}
// Helper Methods
// isEmpty
isEmpty() {
return this.size === 0;
}
// size_Of_List
getSize() {
return this.size;
}
// PrintList
print() {
// set current node
let current = this.head;
// iterate over ll
while (current) {
// console.log every node's data
console.log(current.data);
// set next node to be the current
current = current.next;
}
console.log('-------------');
}
}
module.exports = { Node, LinkedList };
다른 파일에서 Queu를 빌드할 수 있도록 내보내기
Reference
이 문제에 관하여(JS에서 큐 작성(연결 목록 사용)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/petrussola/writing-a-queue-in-js-using-a-linked-list-36p4텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)