What is a stack
A stack is a list of elements only accessible from one end: the top. It is called a LIFO(Last in first out) data structure. Any element not currently at the top of the stack cannot be accessed. To get to an element at the bottom of the stack, all the elements above it must be disposed.
Creating a stack
First we will define the stack class and the constructor. The items array will store the elements of the stack.
class Stack {
constructor(){
this.items=[];
}
};
Next we will define the push() method. This add a new item or items to the top of the stack.
push=(element)=>{
return this.items.push(element);
}
To check the element at the top of the stack, we will define the peek() method.
peek=(element)=>{
return this.items[this.items.length - 1];
}
The pop() function removes and returns the top element from the stack.
pop=()=>{
return this.items.pop();
};
To find how many element are in the stack, we define the size() functions
size=()=>{
return this.items.length;
}
To remove all elements in the stack we define the clear() functions
clear=()=>{
return this.items=[];
}
This is the full code of the Stack class
class Stack {
constructor(){
this.items=[];
}
push=(element)=>{
return this.items.push(element);
}
peek=(element)=>{
return this.items[this.items.length - 1];
}
pop=()=>{
return this.items.pop();
}
size=()=>{
return this.items.length;
}
clear=()=>{
return this.items=[];
}
}
To use the Stack class:
let newStack= new Stack();
//to pop
newStack.pop();
//to add
newStack.push(3);
Use cases of stacks
Palindromes- palindromes are words that are spelled the same way forward as backwards like car, racecar. Stacks can be used to determine if a given word is a palindrome. The original string is pushed onto a stack moving from left to right. When the end of the string is reached, the stack contains the word in reverse order with the top of the stack being the first character and the bottom of the stack being the last letter. The reversed string is compared with the original string; if they are equal then the word is a palindrome.
Multiple base conversions – Stacks can be used to convert a number from one base to another.
Top comments (0)