-
Notifications
You must be signed in to change notification settings - Fork 21
/
stack-with-two-queues.js
64 lines (53 loc) · 1.02 KB
/
stack-with-two-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
63
64
// needs refactoring
/**
* @constructor
*/
var Stack = function() {
this.queue = new Queue();
};
/**
* @param {number} x
* @returns {void}
*/
Stack.prototype.push = function(x) {
var nextQueue = new Queue();
nextQueue.enqueue(x);
nextQueue.enqueue(this.queue);
this.queue = nextQueue;
};
/**
* @returns {void}
*/
Stack.prototype.pop = function() {
var x = this.queue.dequeue();
this.queue = this.queue.dequeue();
return x;
};
/**
* @returns {number}
*/
Stack.prototype.top = function() {
return this.queue.top();
};
/**
* @returns {boolean}
*/
Stack.prototype.empty = function() {
return this.queue.length() === 0;
};
// Wrapper class for Queue. Uses simple list operations
var Queue = function() {
this.lst = [];
}
Queue.prototype.enqueue = function(x) {
this.lst.push(x);
}
Queue.prototype.dequeue = function() {
return this.lst.shift();
}
Queue.prototype.length = function() {
return this.lst.length;
}
Queue.prototype.top = function() {
return this.lst[0];
}