STACK IN JAVASCRIPT
Implement Stack using array
what is stack ?
Stack is a linear data structure it follows LIFO(Last In First Out) or FILO(First In Last Out) principle.⬇️
PUSH( ) METHOD
push method is used to push an element into end of the Stack. If you add an element they pushed/added in top of the stack.⬇️
POP( ) METHOD
The element is popped from the top of the stack and they displayed from your screen.⬇️
UNSHIFT( ) METHOD
unshift() method is used to add one or more elements to the beginning of the given array…….⬇️
SHIFT( ) METHOD
The shift() method removes the first element from an array and returns that removed element……⬇️
isEmpty()
Return true if the stack is empty………⬇️
peek();
peek method shows top most element in stack………⬇️
size()
It returns the length of the current stack…….…⬇️
clear()
It removes all the items from the Stack……..…⬇️
RECAP
EXERCISE TIME:-
Do it yourself…if you get the output comment below
class Stack {
constructor() {
this.items = [];
}
// add element to the stack
add(element) {
return this.items.push(element);
}
// remove element from the stack
remove() {
if(this.items.length > 0) {
return this.items.pop();
}
}
// view the last element
peek() {
return this.items[this.items.length - 1];
}
// check if the stack is empty
isEmpty(){
return this.items.length == 0;
}
// the size of the stack
size(){
return this.items.length;
}
// empty the stack
clear(){
this.items = [];
}
}let stack = new Stack();
stack.add(100);
stack.add(200);
stack.add(400);
console.log(stack.items);stack.remove();
console.log(stack.items);console.log(stack.peek());console.log(stack.isEmpty());console.log(stack.size());stack.clear();
console.log(stack.items);console.log("GIVE A CLAP IF YOU ENJOYED THIS ARTICLE AND FOLLOW FOR MORE. IT MOTIVATES ME A LOT.🤍");
GIVE A CLAP IF YOU ENJOYED THIS ARTICLE AND FOLLOW FOR MORE. IT MOTIVATES ME A LOT.🤍
𝔻𝕠 𝕪𝕠𝕦 𝕨𝕒𝕟𝕥 𝕡𝕒𝕣𝕥-𝟚 𝕔𝕠𝕞𝕞𝕖𝕟𝕥 𝕓𝕖𝕝𝕠𝕨⬇️
THINK TWICE💭-code once!
THANKS_FOR_READING_!🌟
❤️“Have a Fine_Day”❤️