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
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.
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
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);