A simple implementation of the Stack data structure in JavaScript. This repository demonstrates how to create a stack class with essential methods and explains its functionality with practical examples.
A Stack is a data structure that follows the LIFO (Last In, First Out) principle. The last element added to the stack is the first one to be removed. Think of it as a stack of plates: you take the top plate first when serving.
- Push: Add an item to the stack.
- Pop: Remove and return the top item.
- Peek: View the top item without removing it.
- isEmpty: Check if the stack is empty.
- Size: Get the number of items in the stack.
Here’s the JavaScript implementation of the stack:
classStack{constructor(){this.items=[];// Initialize an empty array}// Add an item to the stackpush(element){this.items.push(element);}// Remove and return the top itempop(){if(this.isEmpty()){return"Stack is empty!";}returnthis.items.pop();}// Check if the stack is emptyisEmpty(){returnthis.items.length===0;}// Peek at the top item without removing itpeek(){if(this.isEmpty()){return"Stack is empty!";}returnthis.items[this.items.length-1];}// Get the size of the stacksize(){returnthis.items.length;}}// Initialize the stackconststack=newStack();// Add items to the stackstack.push("Plate 1");stack.push("Plate 2");stack.push("Plate 3");// Peek at the top itemconsole.log(stack.peek());// Output: Plate 3// Remove items from the stackconsole.log(stack.pop());// Output: Plate 3console.log(stack.pop());// Output: Plate 2// Check if the stack is emptyconsole.log(stack.isEmpty());// Output: false// Get the size of the stackconsole.log(stack.size());// Output: 1- Undo/Redo Operations: In text editors and IDEs.
- Backtracking: In algorithms like depth-first search (DFS).
- Expression Evaluation: Managing operands and operators in mathematical expressions.
- Function Call Stack: Handling nested function calls in programming.
Want to see a quick tutorial on how to build this? Check out this TikTok video:
https://www.tiktok.com/@jsmentoring/video/7461022091421273376
- Clone the repository:
git clone https://github.com/your-username/stack-data-structure.git cd stack-data-structure - Open the file
stack.jsin your favorite code editor. - Run the file using Node.js:
node stack.js
Contributions are welcome! If you have suggestions or want to add new features, feel free to create a pull request.
This project is licensed under the MIT License.
- LinkedIn - Vitalii Semianchuk
- Telegram - @jsmentorfree - We do a lot of free teaching on this channel! Join us to learn and grow in web development.
- Tiktok - @jsmentoring Everyday new videos
- Youtube - @jsmentor-uk Mentor live streams
- Dev.to - fix2015 Javascript featured, live, experience