Last active
January 29, 2019 04:48
-
-
Save rxluz/34498d0bc0397659bdc4bbe3593bfc07 to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
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 Stack() { | |
let items = [] | |
class PublicStack { | |
peek() { | |
if (this.isEmpty()) throw new Error('Stack is empty') | |
const lastItemIndex = items.length - 1 | |
return items[lastItemIndex] | |
} | |
pop() { | |
if (this.isEmpty()) throw new Error('Stack is empty') | |
return items.pop() | |
} | |
push(data) { | |
items.push(data) | |
} | |
isEmpty() { | |
return this.size() === 0 | |
} | |
size() { | |
return items.length | |
} | |
} | |
return new PublicStack() | |
} | |
const nextGreaterElement = (list, element) => { | |
//creates a stack that only receives the elements that is located after the current element | |
let elementsAfterStack = new Stack() | |
//controls which elements will be added in element | |
let startAdding = false | |
//loops the list to check what's the elements after the current element | |
list.forEach(currentElement => { | |
// this is runnned before to avoid add the searched number in elementsAfterStack | |
if (startAdding) { | |
elementsAfterStack.push(currentElement) | |
} | |
// case the current element inside the loop be the same searched element sets the start adding to true, with this the numbers in the next interation will be added in stack | |
if (currentElement === element) { | |
startAdding = true | |
} | |
}) | |
// the number could be not found, that's the reason that we define this number as null before starts the loop | |
let nextGreaterElementValue = null | |
/* execute the full loop removing in each interation the top number until there are no numbers inside the stack, | |
always when some number greater than actual is founded replaces the current nextGreaterElementValue to this */ | |
while (!elementsAfterStack.isEmpty()) { | |
if (elementsAfterStack.peek() > element) { | |
nextGreaterElementValue = elementsAfterStack.peek() | |
} | |
// we need remove this item from the stack, with this in the next interation other item will be checked | |
elementsAfterStack.pop() | |
} | |
return nextGreaterElementValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment