-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.js
73 lines (61 loc) · 1.15 KB
/
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
64
65
66
67
68
69
70
71
72
// Node class
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Linked list class
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
append(data) {
const node = new Node(data);
if (!this.head) {
this.head = node;
this.tail = node;
return;
}
this.tail.next = node;
this.tail = node;
}
prepend(data) {
const node = new Node(data);
if (!this.head) {
this.head = node;
this.tail = node;
return;
}
node.next = this.head;
this.head = node;
}
delete(data) {
if (!this.head) {
return;
}
if (this.head.data === data) {
this.head = this.head.next;
return;
}
let current = this.head;
while (current.next) {
if (current.next.data === data) {
current.next = current.next.next;
if (current.next === null) {
this.tail = current;
}
return;
}
current = current.next;
}
}
traverse() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}