-
Notifications
You must be signed in to change notification settings - Fork 1
/
linkedList.js
109 lines (98 loc) · 2.48 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
module.exports = class LinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
shift(value){
let node = this.newNode(value);
if(this.head == null){
this.head = node;
this.tail = node;
}else{
this.head.prev = node;
node.next = this.head;
this.head = node;
}
this.length++;
}
push(value){
let node = this.newNode(value);
if(this.head == null){
this.head = node;
this.tail = node;
}else{
this.tail.next = node;
node.prev = this.tail;
this.tail = node;
}
this.length++;
return node;
}
newNode(value, next = null, tail = null){
let node = {};
node.value = value;
node.next = next;
node.prev = tail;
return node;
}
deleteHead(){
if(this.length == 1){
this.head = null;
this.tail = null;
this.length--;
}else if(this.head == null || this.head.next == null){
return;
}else{
this.head = this.head.next;
this.head.prev = null;
this.length--;
}
}
removeElement(node){
if(node == this.head){
this.deleteHead();
}else if(node == this.tail){
this.deleteTail();
}else if(this.length >= 3){
node.prev.next = node.next;
node.next.prev = node.prev;
this.length--;
}
}
nodeAtIndex(index){
let i = 0;
let currentNode = this.head;
while(i < index){
currentNode = currentNode.next;
i++;
}
return currentNode;
}
value(index){
if(index >= this.length){
return null;
}
return this.nodeAtIndex(index).value;
}
removeElementAtIndex(index){
if(index >= this.length){
return null;
}
let currentNode = this.nodeAtIndex(index);
this.removeElement(currentNode);
}
deleteTail(){
if(this.length == 1){
this.tail = null;
this.head = null;
this.length--;
}else if(this.tail == null || this.tail.prev == null){
return;
}else{
this.tail = this.tail.prev;
this.tail.next = null;
this.length--;
}
}
}