-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdoubly-linked-list.js
62 lines (48 loc) · 1.12 KB
/
doubly-linked-list.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
const Node = require("../Node");
class DoublyLinkedList {
append(data) {
if (!this.head) {
return (this.head = new Node(data));
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = new Node(data);
current.next.previous = current;
}
prepend(data) {
if (!this.head) {
return (this.head = new Node(data));
}
let newHead = new Node(data);
newHead.next = this.head;
newHead.next.previous = newHead;
this.head = newHead;
}
remove(data) {
if (!this.head) return;
if (this.head.data === data) {
this.head = this.head.next;
this.head.previous = null;
return;
}
let current = this.head;
while (current.next) {
if (current.next.data === data) {
current.next = current.next.next;
if (current.next) {
current.next.previous = current;
}
break;
}
current = current.next;
}
}
}
const list = new DoublyLinkedList();
list.append("teste");
list.append("mais um");
list.prepend("Head");
list.remove("teste");
console.log(list.head);