Stack in Javascript
Stack is a linear data structure in which insertion and deletion are done at one end this end is generally called the top. It works on the principle of Last In First Out (LIFO) or First in Last out (FILO). LIFO means the last element inserted inside the stack is removed first. FILO means, the last inserted element is available first and is the first one to be deleted.
- Push: Add an element to the top of a stack
- Pop: Remove an element from the top of a stack
- IsEmpty: Check if the stack is empty
- IsFull: Check if the stack is full
- top/Peek: Get the value of the top element without removing it
Below is the implementation of the Stack in javascript:
// Stack class
class Stack {
// Array is used to implement stack
constructor()
{
this.items = [];
}
// Functions to be implemented
// push(item)
// push function
push(element)
{
// push element into the items
this.items.push(element);
}
// pop function
pop()
{
// return top most element in the stack
// and removes it from the stack
// Underflow if stack is empty
if (this.items.length == 0)
return "Underflow";
return this.items.pop();
}
// peek function
peek()
{
// return the top most element from the stack
// but does'nt delete it.
return this.items[this.items.length - 1];
}
// isEmpty function
isEmpty()
{
// return true if stack is empty
return this.items.length == 0;
}
// printStack function
printStack()
{
var str = "";
for (var i = 0; i < this.items.length; i++)
str += this.items[i] + " ";
return str;
}
}
// creating object for stack class
var stack = new Stack();
// testing isEmpty and pop on an empty stack
// returns false
console.log(stack.isEmpty());
// returns Underflow
console.log(stack.pop());
// Adding element to the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Printing the stack element
// prints [10, 20, 30]
console.log(stack.printStack());
// returns 30
console.log(stack.peek());
// returns 30 and remove it from stack
console.log(stack.pop());
// returns [10, 20]
console.log(stack.printStack());
Output
true Underflow 10 20 30 30 30 10 20
Learn Data Structures with Javascript | DSA using JavaScript Tutorial
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language, and might be your first preference for Client-side as well as Server-side developments. But have you thought about using Javascript for DSA? Learning Data Structures and Algorithms can be difficult when combined with Javascript. For this reason, we have brought to you this detailed DSA tutorial on how to get started with Data Structures with Javascript from scratch.
Table of Content
- What is Data Structure?
- How to start learning Data Structures with Javascript?
- Learn about Complexities
- Learn Data Structures with JavaScript
- Array in javascript
- String in javascript
- Linked List in Javascript
- Stack in Javascript
- Queue in Javascript
- Tree in Javascript
- Priority Queue in Javascript
- Map in Javascript
- Set in Javascript
- Graph in Javascript