-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoubly_Linked_List.js
94 lines (86 loc) · 2.83 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
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
89
90
91
92
93
94
// ****************************************************************************
class Node {
constructor(value) {
this.value = value;
this.next = null;
this.prev = null;
}
}
// ****************************************************************************
class LinkedList {
// ------------------------------------------------------------------------
constructor(value) {
let newNode = new Node(value);
this.head = newNode;
this.tail = this.head;
this.length = 1;
}
// ------------------------------------------------------------------------
append(value) {
const newNode = new Node(value);
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
// ------------------------------------------------------------------------
prepend(value) {
const newNode = new Node(value);
newNode.next = this.head;
this.head.prev = newNode;
this.length++;
this.head = newNode;
return this;
}
// ------------------------------------------------------------------------
insert(index, value) {
if(index >= this.length) return this.append(value);
const newNode = new Node(value);
const prevNode = this.traverseToIndex(index - 1);
const nextNode = prevNode.next;
newNode.prev = prevNode;
prevNode.next = newNode;
newNode.next = nextNode;
nextNode.prev = newNode;
return this;
}
// ------------------------------------------------------------------------
remove(index) {
if(index >= this.length || index < 0) return this;
const prevNode = this.traverseToIndex(index-1);
const unwantedNode = prevNode.next;
const nextNode = unwantedNode.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
this.length--;
return this;
}
// ------------------------------------------------------------------------
traverseToIndex(index) {
let currentNode = this.head;
while(index !== 0) {
currentNode = currentNode.next;
index--;
}
return currentNode;
}
// ------------------------------------------------------------------------
printList() {
const array = [];
let currentNode = this.head;
while(currentNode !== null) {
array.push(currentNode.value);
currentNode = currentNode.next;
}
console.log(array);
}
};
// ****************************************************************************
const myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.prepend(1);
myLinkedList.insert(2, 99);
myLinkedList.remove(2);
myLinkedList.printList();