How Do You Implement a Stack and a Queue in Javascript?

How to Implement a Stack and a Queue in JavaScript

As a JavaScript developer, you may often come across situations where you need to implement data structures like stacks and queues. These data structures play a crucial role in managing and organizing data efficiently. In this article, we will explore how to implement a stack and a queue in JavaScript, along with code examples for each.

Implementing a Stack

A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. It means that the last element added to the stack will be the first one to be removed. Here’s a simple implementation of a stack using an array:


class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    if (this.isEmpty()) {
      return "Underflow";
    }
    return this.items.pop();
  }

  isEmpty() {
    return this.items.length === 0;
  }

  peek() {
    if (this.isEmpty()) {
      return "No elements in the stack";
    }
    return this.items[this.items.length - 1];
  }

  size() {
    return this.items.length;
  }

  clear() {
    this.items = [];
  }
}

// Example usage
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);

console.log(stack.pop()); // Output: 30
console.log(stack.peek()); // Output: 20
console.log(stack.size()); // Output: 2
console.log(stack.isEmpty()); // Output: false
stack.clear();
console.log(stack.isEmpty()); // Output: true

Implementing a Queue

A queue is a data structure that follows the First-In-First-Out (FIFO) principle. It means that the first element added to the queue will be the first one to be removed. Here’s a simple implementation of a queue using an array:


class Queue {
  constructor() {
    this.items = [];
  }

  enqueue(element) {
    this.items.push(element);
  }

  dequeue() {
    if (this.isEmpty()) {
      return "Underflow";
    }
    return this.items.shift();
  }

  isEmpty() {
    return this.items.length === 0;
  }

  front() {
    if (this.isEmpty()) {
      return "No elements in the queue";
    }
    return this.items[0];
  }

  size() {
    return this.items.length;
  }

  clear() {
    this.items = [];
  }
}

// Example usage
const queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

console.log(queue.dequeue()); // Output: 10
console.log(queue.front()); // Output: 20
console.log(queue.size()); // Output: 2
console.log(queue.isEmpty()); // Output: false
queue.clear();
console.log(queue.isEmpty()); // Output: true

Now that you have seen the implementations of both a stack and a queue in JavaScript, you can utilize these data structures to efficiently manage and manipulate your data. Remember to choose the appropriate data structure based on your specific requirements.

Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *