-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctci-3.4-queue-via-stacks.js
53 lines (46 loc) · 1.18 KB
/
ctci-3.4-queue-via-stacks.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
//We create 2 stacks one for enqueue and one for dequeue.
//Once dequeue stack is empty, we pull all elements from enqueue stack onto dequeue stack;
class MyQueue {
constructor(capacity) {
this._capacity = capacity || Infinity;
this._dequeue = [];
this._enqueue = [];
}
enqueue(element) {
if (this._enqueue.length < this._capacity) {
this._enqueue.push(element);
return;
}
return "Queue capacity is full.";
}
dequeue() {
if (this._dequeue.length <= 0) {
while (this._enqueue > 0) {
this._dequeue.push(this._enqueue[0]);
this._enqueue.shift();
}
}
this._dequeue.shift();
}
peek() {
if (this._dequeue.length <= 0) {
if (this._enqueue.length > 0) {
return this._enqueue[0];
}
return "Queue is empty";
}
return this._dequeue[0];
}
count() {
return this._enqueue.length + this._dequeue.length;
}
contains(element) {
for (let i = 0; i < this._enqueue.length; i++) {
if (this._enqueue[i] === element) return true;
}
for (let i = 0; i < this._dequeue.length; i++) {
if (this._dequeue[i] === element) return true;
}
return false;
}
}