Implement Queue interface using Stack interface as a storage
// Implement Queue interface using Stack interface as a storage
function queue() {
this.stack = [];
}
queue.prototype.enq = function(item) {
this.stack.push(item);
}
queue.prototype.deq = function() {
if (this.stack.length == 0) {
return null;
}
if (this.stack.length == 1) {
return this.stack.pop();
} else {
let pulled = this.stack.pop();
let res = this.deq();
this.stack.push(pulled);
return res;
}
}
console.log('=====');
let q = new queue();
q.enq(1);
q.enq(2);
q.enq(3);
q.enq(4);
console.log(q.deq()); // 1
console.log(q.deq()); // 2
console.log(q.deq()); // 3
console.log(q.deq()); // 4
console.log(q.deq()); // null
console.log(q.deq()); // null
console.log(q.stack);