-
Notifications
You must be signed in to change notification settings - Fork 0
/
queues.js
88 lines (51 loc) · 1.1 KB
/
queues.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
/*Queue - FIFO Data Structure */
// var q = []
// q.push("First")
// q.push("Second")
// console.log(q);
// q.pop()
// console.log(q);
class Node {
constructor(value) {
this.value = value
this.next = null
}
}
class Queue {
constructor() {
this.first = null
this.last = null
this.size = 0
}
enqueue(val) { //add to the end
var newNode = new Node(val)
if(!this.first) {
this.first = newNode
this.last = newNode
} else {
this.last.next = newNode
this.last = newNode
}
return ++this.size
}
dequeue(){ //remove from the beginning
if(!this.first) return null
var temp = this.first
if(this.first === this.last) {
this.last = null
}
this.first = this.first.next
this.size--
return temp.value
}
}
var q = new Queue()
q.enqueue("First")
q.enqueue("Second")
console.log(q);
/*Time Complexity
Insertion - O(1)
Removal - O(1)
Searching - O(n)
Access - O(n)
*/