Created
March 21, 2016 20:13
-
-
Save dobakay/f74ccf17ab710fc784cd to your computer and use it in GitHub Desktop.
sort a stack with another stack
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
'use strict'; | |
function print(arr) { | |
var res = ''; | |
for (var i = 0; i < arr.length; i++) { | |
res += arr[i]; | |
}; | |
return res; | |
} | |
function sortStack(stack) { | |
var resultStack = []; | |
while(!!stack.length) { | |
var tmp = stack.pop(); | |
while(!!resultStack.length && tmp > resultStack[resultStack.length-1]) { | |
var resultStackPeek = resultStack.pop(); | |
stack.push(resultStackPeek); | |
} | |
resultStack.push(tmp); | |
console.log('stack: %s resultStack: %s', print(stack), print(resultStack)); | |
} | |
return resultStack; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment