Created
December 31, 2015 06:58
-
-
Save jinwolf/cb1a560944291092dd28 to your computer and use it in GitHub Desktop.
Queue implementation using two stacks (JavaScript)
This file contains hidden or 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 Queue() { | |
var inStack = []; | |
var outStack = []; | |
this.enqueue = function(num) { | |
inStack.push(num); | |
} | |
this.dequeue = function() { | |
if (outStack.length > 0) { | |
return outStack.pop(); | |
} | |
while(inStack.length > 1) { | |
outStack.push(inStack.pop()); | |
} | |
return inStack.pop(); | |
} | |
} | |
var queue = new Queue(); | |
queue.enqueue(1); | |
queue.enqueue(2); | |
queue.enqueue(3); | |
console.log(queue.dequeue()); | |
console.log(queue.dequeue()); | |
queue.enqueue(4); | |
queue.enqueue(5); | |
console.log(queue.dequeue()); | |
console.log(queue.dequeue()); | |
console.log(queue.dequeue()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment