Stack
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
if (this.isEmpty()) {
return null;
} else {
return this.items.pop();
}
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
const myStack = new Stack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
console.log(myStack.pop()); // Output: 3
console.log(myStack.pop()); // Output: 2
console.log(myStack.pop()); // Output: 1
console.log(myStack.pop()); // Output: null
Queue
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) {
return null;
} else {
return this.items.shift();
}
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
// Example usage of the queue
const myQueue = new Queue();
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);
console.log(myQueue.dequeue()); // Output: 1
console.log(myQueue.dequeue()); // Output: 2
console.log(myQueue.dequeue()); // Output: 3
console.log(myQueue.dequeue()); // Output: null