[Snow-ball]프로그래밍(컴퓨터)/자료구조
JavaScript로 Linked List (연결 리스트) 구현해보기 !!
Snow-ball
2023. 7. 14. 00:26
반응형
자바스크립트로 연결리스트를 구현해보았다.
4가지 기능을 구현해보았다.
1. insert (추가)
2. insertHead (헤드 쪽에 추가)
3. remove (삭제)
4. find (해당 노드 찾기)
코드
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
class Node {
constructor(data = null, tail = null) {
this.data = data;
this.tail = tail;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
insert(data, index = 0) {
let findIndex = this.size >= index ? index : null;
if (this.size === 0) {
this.head = new Node(data);
this.size++;
return;
}
if (!findIndex && findIndex !== 0)
throw new Error("리스트 사이즈 확인이 필요합니다.");
const newNode = new Node(data);
let currentNode = this.head;
let prevNode = null;
while (findIndex) {
prevNode = currentNode;
currentNode = currentNode.tail;
findIndex--;
}
if (!!currentNode) {
newNode.tail = currentNode.tail;
currentNode.tail = newNode;
} else {
prevNode.tail = newNode;
}
this.size++;
}
insertHead(data) {
if (this.size === 0) {
this.head = new Node(data);
this.size++;
return;
}
const newNode = new Node(data);
let currentNode = this.head;
this.head = newNode;
newNode.tail = currentNode;
}
remove(index) {
let findIndex = this.size > index ? index : null;
if (!findIndex) throw new Error("리스트 사이즈 확인이 필요합니다.");
let currentNode = this.head;
let prevNode = null;
while (findIndex) {
prevNode = currentNode;
currentNode = currentNode.tail;
findIndex--;
}
prevNode.tail = currentNode.tail;
this.size--;
}
find(index) {
let findIndex = this.size > index ? index : null;
if (!findIndex) throw new Error("리스트 사이즈 확인이 필요합니다.");
let currentNode = this.head;
while (findIndex > 0) {
currentNode = currentNode.tail;
findIndex--;
}
console.log(currentNode);
}
}
|
cs |
반응형