Last active
January 23, 2017 16:11
-
-
Save bernbecht/1115f48543c1627b250bb05ba22560b4 to your computer and use it in GitHub Desktop.
Queue using 2 stacks in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Stack() { | |
this._size = 0; | |
this._storage = {}; | |
} | |
Stack.prototype.push = function(data) { | |
var size = ++this._size; //returns i++ | |
this._storage[size] = data; | |
return size; | |
} | |
Stack.prototype.pop = function() { | |
var size = this._size, | |
deletedData = this._storage[size]; | |
delete this._storage[size]; | |
this._size--; | |
return deletedData; | |
} | |
function Queue() { | |
this._inbox = new Stack(), | |
this._outbox = new Stack(); | |
} | |
Queue.prototype.dequeue = function() { | |
if (this._inbox._size == 1) { | |
return this._inbox.pop(); | |
} | |
if (this._outbox._size == 0) { | |
var inboxLength = this._inbox._size; | |
for (var i = 1; i <= inboxLength; i++) { | |
this._outbox.push(this._inbox.pop()); | |
} | |
} | |
return this._outbox.pop(); | |
} | |
Queue.prototype.enqueue = function(data) { | |
this._inbox.push(data); | |
} | |
var q = new Queue(); | |
console.log(q.enqueue('1')); | |
console.log(q.enqueue('2')); | |
console.log(q.enqueue('3')); | |
console.log(q._inbox); | |
console.log(q.dequeue()); | |
console.log(q._inbox); | |
console.log(q._outbox); | |
console.log(q.dequeue()); | |
console.log(q._inbox); | |
console.log(q._outbox); | |
console.log(q.dequeue()); | |
console.log(q._inbox); | |
console.log(q._outbox); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment