연결 리스트란
각 노드가 데이터와 포인터를 가지고 한 줄로 연결된 방식으로 데이터를 저장하는 자료구조이다.
javaScript에서는 파이썬과는 다르게 큐나 트리 자료구조 관련 기본 라이브러리가 없어 직접 구현해야 한다.
그리고 그 자료구조를 구현하기에 연결 리스트가 사용된다.
연결 리스트 구현
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
size() {
let count = 0;
let currentNode = this.head;
while (currentNode) {
count++;
currentNode = currentNode.next;
}
return count;
}
find(value) {
let current = this.head;
while (current?.value !== value && current) {
current = current.next;
}
return current;
}
append(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
removeFirst() {
const value = this.head.value;
this.head = this.head.next;
return value;
}
}
'웹 > JS' 카테고리의 다른 글
코딩테스트를 위한 JavaScript : Queue (0) | 2023.09.23 |
---|---|
코딩테스트를 위한 JavaScript : 형변환 (0) | 2023.09.15 |
코딩테스트를 위한 JavaScript 문법 : Math 클래스 (0) | 2023.09.14 |
코딩테스트를 위한 JavaScript 문법: String (2) | 2023.09.14 |
코딩테스트를 위한 JavaScript 문법: Object (0) | 2023.09.12 |
댓글