작성
·
114
0
prev와 tail을 이용해서 만들어 봤습니다!
궁금한점이 하나 있는데 remove 메서드의 if (current)의 else 부분은 필요하지 않은것 같아서 구현하지 않았는데 문제가 있지는 않나요?
class LinkedList {
length = 0;
head = null;
tail = null;
add(value) {
const newNode = new Node(value);
if (this.head) {
this.tail.next = newNode;
this.tail = newNode;
} else {
this.head = newNode;
this.tail = newNode;
}
this.length++;
return this.length;
}
search(index) {
return this.#search(index)[1]?.value;
}
prevSearch(index) {
return this.#search(index)[0]?.value;
}
#search(index) {
let count = 0;
let prev;
let current = this.head;
while(count < index) {
prev = current;
current = current?.next;
count++;
}
return [prev, current];
}
remove(index) {
const [prev, current] = this.#search(index);
if (current) {
if (prev) {
prev.next = current.next;
}
if (current.next) {
current.next.prev = prev;
}
if (current === this.tail) {
this.tail = prev;
}
}
this.length--;
return this.length;
}
}
class Node {
next = null;
prev = null;
constructor(value) {
this.value = value;
}
}
const li = new LinkedList();
li.add(1);
li.add(2);
li.add(3);
li.add(4);
li.add(5);
li.add(6);
console.log(li.prevSearch(2));
console.log(li.remove(4));
console.log(li.search(4));
console.log(li.tail.value);
console.log(li.remove(3));
console.log(li.tail.value);
console.log(li.remove(3));
console.log(li.tail.value);
console.log(li.remove(2));
console.log(li.remove(1));
console.log(li.tail.value);
console.log(li.remove(0));