Hey all,
I am trying to learn how to implement a queue with two stacks but I can’t figure out why when I enqueue into the two stack, I am getting undefined. Can someone assist and give a second perspective on my code. Am I calling it wrong or is the code wrong?
function Stack(capacity) {
this._capacity = capacity || Infinity;
this._storage = {};
this._count = 0;
}
Stack.prototype.push = function(value) {
if(this._count < this._capacity) {
this._storage[this._count++] = value;
return this._count;
}
return 'Max capacity already reached. Remove element before adding a new one.'
};
Stack.prototype.pop = function() {
var value = this._storage[--this._count];
delete this._storage[this._count];
if (this._count < 0) {
this._count = 0;
}
return value;
}
Stack.prototype.peek = function() {
return this._storage[this._count - 1];
};
Stack.prototype.count = function() {
return this._count;
}
function Queue_TwoStacks() {
this._inbox = new Stack();
this._outbox = new Stack();
}
Queue_TwoStacks.prototype.enqueue = function(value) {
this._inbox.push(value);
};
Queue_TwoStacks.prototype._transferStacks = function() {
while (this._inbox.count() > 0) {
this._outbox.push(this._inbox.pop());
}
};
Queue_TwoStacks.prototype.dequeue = function() {
if (this._outbox.count() === 0) this._transferStacks();
return this._outbox.pop();
};
Queue_TwoStacks.prototype.count = function() {
return this._inbox.count() + this._outbox.count();
};
Queue_TwoStacks.prototype.peek = function() {
if (this._outbox.count() === 0) this._transferStacks();
return this._outbox.peek();
};
var myQueue_TwoStacks = new Queue_TwoStacks();
console.log(myQueue_TwoStacks.enqueue(1), 'should be 1');
//outputs: `undefined 'should be 1'` instead of `1 'should be 1'`