-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked-list.js
More file actions
114 lines (101 loc) · 2.24 KB
/
Copy pathlinked-list.js
File metadata and controls
114 lines (101 loc) · 2.24 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
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
110
111
112
113
114
class Node{
constructor(value){
this.value = value;
this.previous = null;
this.next = null;
}
}
export default class LinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
// Insert value at back
push(value){
const node = new Node(value);
if(!this.head){
this.head = node;
this.tail = node;
} else{
node.previous = this.tail;
this.tail.next = node;
this.tail = node;
}
this.length++;
}
// Remove value at back
pop(){
if(!this.head) return null;
const previousNode = this.tail.previous;
const oldTailValue = this.tail.value;
if(previousNode){
previousNode.next = null;
this.tail = previousNode;
} else{
this.head = null;
this.tail = null;
}
this.length--;
return oldTailValue;
}
// Remove value at front
shift(){
if(!this.head) return null;
const nextNode = this.head.next;
const oldHeadValue = this.head.value;
if(nextNode){
nextNode.previous = null;
this.head = nextNode;
} else{
this.head = null;
this.tail = null;
}
this.length--;
return oldHeadValue;
}
// Insert value at front
unshift(value){
const node = new Node(value);
if(!this.head){
this.head = node;
this.tail = node;
} else{
this.head.previous = node;
node.next = this.head;
this.head = node;
}
this.length++;
}
/*
* Given a specific value,
* finds this value and removes it.
* If can't find it, list remains the same
*/
delete(value){
if(this.head.value == value){
this.shift();
} else if(this.tail.value == value){
this.pop();
} else {
let currentNode = this.head.next;
while(true){
if(currentNode == null) break;
if(currentNode.value == value){
currentNode.next.previous = currentNode.previous;
currentNode.previous.next = currentNode.next;
currentNode.previous = null;
currentNode.next = null;
this.length--;
break;
} else{
currentNode = currentNode.next;
}
}
}
}
// Number of values in doubly linked list
count(){
return this.length;
}
}