Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Created October 15, 2018 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitkarpov/35ff143d03a13df9fad56f748c563d91 to your computer and use it in GitHub Desktop.
Save vitkarpov/35ff143d03a13df9fad56f748c563d91 to your computer and use it in GitHub Desktop.
Removing an arbitrary element from the stack
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