Creating a stack
We are going to create our own class to represent a stack. Let's start from the basics and declare our class:
function Stack() { //properties and methods go here }
First, we need a data structure that will store the elements of the stack. We can use an array to do this:
var items = [];
Next, we need to declare the methods available for our stack:
push(element(s))
: This adds a new item (or several items) to the top of the stack.pop()
: This removes the top item from the stack. It also returns the removed element.peek()
: This returns the top element from the stack. The stack is not modified (it does not remove the element; it only returns the element for information purposes).isEmpty()
: This returnstrue
if the stack does not contain any elements andfalse
if the size of the stack is bigger than 0.clear()
: This removes all the elements of the stack.size()
: This returns how many elements the stack contains. It is similar to thelength
property of an array.
The first method...