Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Stacks

data structure - stacks

What are stacks?
  1. The stacks are Last in First out (LIFO) data structures
  2. Stack is like a pile of plates
  3. In the beginning, the pile may be empty, but eventually, a plate can be added to the pile
  4. Only the most recently added plate can be removed first
  5. Which is (LIFO) the last plate in is the first plate out
  6. It has a bottom and top plate
  7. Operations stack: Pop, Push, Lookup
  8. Stacks are used to implementing functions, parsers, expression evaluation, and backtracking algorithms
Where stacks are used?
Stacks are used to implementing
  1. Functions,
  2. Parsers,
  3. Expression evaluation,
  4. 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: [] }