Monday, January 13, 2025
HomeProgrammingHow do you implement a Stack and a Queue in JavaScript?

How do you implement a Stack and a Queue in JavaScript?

Here’s how to implement a Stack and a Queue in JavaScript:

Stack Implementation

A stack operates on a Last In, First Out (LIFO) principle.

Using an Array:

javascript

Copy code

class Stack {

constructor() {

this.items = [];}

// Add an element to the stack

push(element) {

this.items.push(element);}

// Remove and return the top element

pop() {  if (this.isEmpty()) { return “Stack is empty”; } return this.items.pop();}

// Peek at the top element without removing it

See also  How do I determine the size of my array in C?

peek() {  if (this.isEmpty()) {

return “Stack is empty”;  }

return this.items[this.items.length – 1]; }

// Check if the stack is empty

isEmpty() {

return this.items.length === 0; }

// Get the size of the stack

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

// Clear the stack

clear() {

this.items = []; }}

// Example usage:

const stack = new Stack();

stack.push(10);

stack.push(20);

console.log(stack.pop()); // 20

console.log(stack.peek()); // 10

Queue Implementation

A queue operates on a First In, First Out (FIFO) principle.

See also  Dictionary Class in Java

Using an Array:

javascript

Copy code

class Queue {

constructor() {

this.items = [];

}

 

// Add an element to the queue

enqueue(element) {

this.items.push(element);

}

 

// Remove and return the front element

dequeue() {

if (this.isEmpty()) {

return “Queue is empty”;

}

return this.items.shift();

}

// Peek at the front element without removing it

front() {

if (this.isEmpty()) {

return “Queue is empty”;

}

return this.items[0];

}

// Check if the queue is empty

See also  Finding Duplicate Values in a SQL Table

isEmpty() {

return this.items.length === 0;

}

// Get the size of the queue

size() {

return this.items.length;

}

// Clear the queue

clear() {

this.items = [];

}

}

// Example usage:

const queue = new Queue();

queue.enqueue(10);

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x