-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueFromStack.js
More file actions
38 lines (35 loc) · 824 Bytes
/
QueueFromStack.js
File metadata and controls
38 lines (35 loc) · 824 Bytes
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
// Create a stack and then create a queue using 2 stacks
const Stack = () => {
let storage = []
let count = 0
this.push = function(val) {
storage[count] = val;
count++;
};
this.pop = () => {
return storage.pop();
count--;
};
this.size = () => {
return storage.length;
};
};
const Queue = () => {
// create two Stacks
let inbox = new Stack()
let outbox = new Stack()
// push new elements to the inbox
this.enqueue = (val) => {
inbox.push(val)
};
// dequeue will check the outbox. IF it's empty then we push all our inbox items into the outbox
// and pop off the outbox. We then return this popped off item.
this.dequeue = () => {
if(!outbox.size()) {
while(inbox.size()) {
outbox.push(inbox.pop())
}
}
return outbox.pop()
}
}