-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataStructure_LinkedList.js
63 lines (58 loc) · 1.27 KB
/
DataStructure_LinkedList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class LinkedList {
constructor() {
this.length = 0;
this.head = null;
this.tail = null;
}
add(value) {
if (this.head) {
// while문을 탈출한 다음은 next가 null인 상태!
this.current.next = new Node(value);
} else {
this.head = new Node(value);
this.tail = this.head.next;
}
this.length++;
return this.length; // add하면서 길이 늘어나는거 확인하라고 length 반환.
}
search(index) {
return this.#search(index)[1]?.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 (prev && current) {
prev.next = current?.next;
this.length--;
return this.length;
} else if (current) {
// index가 0일 때,
this.head = current.next;
}
// 삭제하고자 하는 대상이 없을 때,
// 아무것도 안 함
}
}
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
const ll = new LinkedList();
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);
console.log(ll);
console.log(ll.search(3));