-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueueStack.js
More file actions
44 lines (35 loc) · 750 Bytes
/
queueStack.js
File metadata and controls
44 lines (35 loc) · 750 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
39
40
41
42
43
44
// Implement a queue using two stacks.
var Stack = function() {
var storage = [];
this.push = function(val){
storage.push(val)
};
this.pop = function(){
return storage.pop();
};
this.size = function(){
return storage.length;
};
};
var Queue = function() {
var inbox = new Stack();
var outbox = new Stack();
this.enqueue = function(val){
inbox.push(val)
};
this.dequeue = function(){
var size = inbox.size();
for (var i = 0; i < size; i++) {
outbox.push(inbox.pop());
}
var result = outbox.pop();
size = outbox.size();
for (var i = 0; i < size; i++){
inbox.push(outbox.pop());
}
return result;
};
this.size = function(){
return inbox.size();
};
};