A Stack follows the Last-In-First-Out (LIFO) principle
January 28, 2024 2:57 PM
A Stack is another type of data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element that is added to the stack will be the first one to be removed.
Think of it like a stack of plates. The last plate you put on the stack is the first one you would take off when you need a plate.
In terms of programming, a stack typically has the following operations:
Push: This operation adds an element to the top of the stack.
Pop: This operation removes an element from the top of the stack.
Peek/Top: This operation returns the top element of the stack without removing it.
IsEmpty: This operation checks if the stack is empty.
Here's a simple implementation of a stack in JavaScript:
class Stack {constructor() {this.items = [];}// Add an element to the top of the stackpush(element) {this.items.push(element);}// Remove an element from the top of the stackpop() {if (this.isEmpty()) return 'Underflow';return this.items.pop();}// Get the top element of the stackpeek() {if (this.isEmpty()) return 'No elements in Stack';return this.items[this.items.length - 1];}// Check if the stack is emptyisEmpty() {return this.items.length == 0;}}
Comments