Stack:-
A Stack is a commonly used linear data structure a stack data structure follows particular operations that are performed Stack is behaved like Last in first out (LIFO) In this, we have three basic operations.
- Push Method
- Pop Method
- Peek Method
- Is Empty Method
Push Method :
The push method is adding data into any type of data into the stack.
Peek Method:
Peek is a very easy operation this method is given you which item or data is on the top of the list so this peek method returns the top element
Pop Method:
Pop is removed the top item from the stack
Is Empty Method:
The is empty method is very important this return if the stack is empty then its return true.
When we use push D is added then call stack on top is D then we use pop then D is removed from the stack.
Stack example using Javascript
//© Inspiration from coding garden
class Stack {
constructor(){
this.data = {};
this.size = 0;
}
push(item){
this.data[this.size] = item;
this.size +=1
}
peek(){
return this.data[this.size - 1];
}
pop(){
const item = this.peek();
this.size -= 1;
delete this.data[this.size];
return item;
}
}
const launguage = new Stack();
launguage.push("Typescript")
launguage.push("Angular");
launguage.push("JS");
launguage.push("C++");
console.log(launguage)
console.log(launguage.pop())
console.log(launguage)
console.log(launguage.pop())
console.log(launguage)
Output
I hope you like this also comments about your thoughts.
For more content follow me on Instagram @developer_nikhil27.
If you want to more support me then buy me a coffee.
Thank you.
Top comments (2)
Hi there and thanks for your article, I also like to train my data algorithm in JavaScript. I tend to try and implement them using only functions and recursion if needed. Here is my attempt I wanted to share with you.
Not the easiest to read given I used the comma operator pretty much for every method but it gets the job done using some one-liners.
Good 👍👍