Created
October 15, 2018 16:43
-
-
Save vitkarpov/35ff143d03a13df9fad56f748c563d91 to your computer and use it in GitHub Desktop.
Removing an arbitrary element from the 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
function removeItemFromStack(stack, item) { | |
const tmp = stack.pop(); | |
// if we've looked up the whole stack there's no item | |
// just return tmp element back to the top and we're done | |
if (stack.length === 0) { | |
stack.push(tmp); | |
return; | |
} | |
// if the current top doesn't equal to item let's go further recursively | |
// when the execution comes back don't forget to get back tmp to its origin place, e.g the current top of the stack | |
if (tmp !== item) { | |
removeItemFromStack(stack, item); | |
stack.push(tmp); | |
} | |
// at this point we have found the item | |
// this means stop calling recursively and start getting back on functions call stack | |
// the item will disappear because of we don't push it back | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment