-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5-queue-using-class.js
More file actions
67 lines (55 loc) · 1.46 KB
/
5-queue-using-class.js
File metadata and controls
67 lines (55 loc) · 1.46 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
/*
================================================================
Enqueue Pseudocode:
-----------------------
1) This function accepts some value.
2) Create a new nonde using that value passed to the function.
3) If there are no nodes in the queue, set this node to be the
first and last property of the queue.
Dequeue Pseudocode:
-----------------------
1) If there is no first property, just return null.
2) Store the first property in a variable.
3) See if the first is the same as the last (check if there is
only 1 node). If so, set teh first and last node to be null.
4) If there is more than 1 node, set the first property to
be the next property of first.
5) Decrement the size by 1.
6) Return the value of the node dequeued.
================================================================
*/
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
enqueue(val) {
let 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() {
if (!this.first) return null;
let currentNode = this.first;
if (this.first === this.last) {
this.last = null;
}
this.first = this.first.next;
this.size--;
return currentNode.value;
}
}
let queue = new Queue();