Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Min max stack example #768

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions contents/stacks_and_queues/code/javascript/min-max-stack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class MinMaxStack {
constructor(){
this.minMaxStack =[];
this.stack = [];
}
peek(){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This chapter uses the words top and front for stacks and queues. Maybe rename peek to top to use the same words as used in the chapter?

return this.stack[this.stack.length -1];
}

pop(){
this.minMaxStack.pop();
return this.stack.pop();
}

push(number){
const newMinMax = { min:number, max:number };
if(this.minMaxStack.length){
const lastMinMax = this.minMaxStack[this.minMaxStack.length-1];
newMinMax.min = Math.min(lastMinMax.min, number);
newMinMax.max = Math.max(lastMinMax.max, number);
}
this.minMaxStack.push(newMinMax);
this.stack.push(number);
}

getMin(){
return this.minMaxStack[this.minMaxStack.length-1].min;
}

getMax(){
return this.minMaxStack[this.minMaxStack.length-1].max;
}
};
11 changes: 11 additions & 0 deletions contents/stacks_and_queues/stacks_and_queues.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@ For the most part, though, queues and stacks are treated the same way. There mus

The notation for this depends on the language you are using. Queues, for example, will often use `dequeue()` instead of `pop()` and `front()` instead of `top()`. You will see the language-specific details in the source code under the algorithms in this book, so for now it's simply important to know what stacks and queues are and how to access elements held within them.

## Example Code

{% method %}
{% sample lang="js" %}
[import, lang:"javascript"](code/javascript/min-max-stack.js)
{% endmethod %}

<script>
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
</script>

## License

##### Code Examples
Expand Down