Stacks

What are stacks?
- The stacks are Last in First out (LIFO) data structures
- Stack is like a pile of plates
- In the beginning, the pile may be empty, but eventually, a plate can be added to the pile
- Only the most recently added plate can be removed first
- Which is (LIFO) the last plate in is the first plate out
- It has a bottom and top plate
- Operations stack: Pop, Push, Lookup
- Stacks are used to implementing functions, parsers, expression evaluation, and backtracking algorithms
Where stacks are used?
Stacks are used to implementing
- Functions,
- Parsers,
- Expression evaluation,
- Backtracking algorithms
Write a code
Let’s implement a stack in javascript
// Stack in Javascript
class Stack {
constructor() {
this.stackContainer = [];
}
push(data) {
this.stackContainer.push(data);
return this;
}
pop() {
this.stackContainer.pop();
return this;
}
}
const stackInstance = new Stack();
stackInstance.push('John');
console.log(stackInstance);
stackInstance.push('Stark');
console.log(stackInstance);
stackInstance.pop();
console.log(stackInstance);
stackInstance.pop();
console.log(stackInstance);
// Outputs
//Stack { stackContainer: [ 'John' ] }
//Stack { stackContainer: [ 'John', 'Stark' ] }
//Stack { stackContainer: [ 'John' ] }
//Stack { stackContainer: [] }