-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList.js
More file actions
80 lines (77 loc) · 1.82 KB
/
DoublyLinkedList.js
File metadata and controls
80 lines (77 loc) · 1.82 KB
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
class Node {
constructor(element) {
this.element = element;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
insert(position, element) {
if (position >= 0 && position <= this.length) {
const node = new Node(element);
let current = this.head,
previous = null,
index = 0;
if (position === 0) {
if (!head) {
this.head = current;
this.tail = node;
} else {
node.next = current;
this.head = node;
current.prev = node;
}
} else if (position === this.length) {
current = this.tail;
current.next = node;
node.prev = current;
this.tail = node;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
current.prev = node;
node.prev = previous;
}
this.length++;
return true;
}
return false;
}
removeAt(position) {
if (position > -1 && position < this.length) {
let current = this.head,
previous = null,
index = 0;
if (position === 0) {
this.head = this.head.next;
this.head.prev = null;
if (this.length === 1) {
this.tail = null;
}
} else if (position === this.length - 1) {
this.tail = this.tail.prev;
this.tail.next = null;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
current.next.prev = previous;
}
this.length--;
return current.element;
} else {
return null;
}
}
}