function singleLinkedListNode(data) {
this.data = data;
this.next = null;
}
class singleLinkedList {
constructor() {
this.head = null;
this.size = 0;
}
isEmpty() {
return this.size === 0;
}
insert(value) {
if (this.head === null) {
this.head = new singleLinkedListNode(value);
} else {
const temp = this.head;
this.head = new singleLinkedListNode(value);
this.head.next = temp;
}
this.size++;
}
remove(value) {
let currentHead = this.head;
if (currentHead.data === value) {
this.head = currentHead.next;
this.size--;
} else {
let prev = currentHead;
while (currentHead.next) {
if (currentHead.data === value) {
prev.next = currentHead.next;
prev = currentHead;
currentHead = currentHead.next;
break;
}
prev = currentHead;
currentHead = currentHead.next;
}
if (currentHead.data === value) {
prev.next = null;
}
this.size--;
}
}
deleteHead() {
const toReturn = null;
if (this.head !== null) {
toReturn = this.head.data;
this.head = this.head.next;
this.size--;
}
return toReturn;
}
find(value) {
const currentHead = this.head;
while (currentHead.next) {
if (currentHead.data === value) {
return true;
}
currentHead = currentHead.next;
}
return false;
}
}
코드를 작성할 때 prototype에다가 넣어볼까 했는데 지금 class를 공부하고 있는중이라 class로 만들어서 해봤는데 이론을 실전에 대입하니까 상당히 괜찮은것 같다.
알고리즘 정리는 어디서 보시는 거에요.. 상당하네요 정리가