JavaScript(JS) JS implement a stack
www.igifditea.com
In JavaScript/JS, you can implement a stack data structure using an array and a set of methods to manipulate it. Here's an example implementation of a stack:
class Stack {
constructor() {
this.items = [];
}
// Push element to the top of the stack
push(element) {
this.items.push(element);
}
// Pop the top element from the stack and return it
pop() {
if (this.isEmpty()) {
return null;
}
return this.items.pop();
}
// Peek the top element in the stack without removing it
peek() {
if (this.isEmpty()) {
return null;
}
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 myStack = new Stack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
console.log(myStack.peek()); // Output: 3
console.log(myStack.pop()); // Output: 3
console.log(myStack.size()); // Output: 2
In this example, we define a class called Stack with an items array property that will hold our stack elements. We then define a set of methods to manipulate the stack:
push(element): adds an element to the top of the stackpop(): removes and returns the top element from the stackpeek(): returns the top element in the stack without removing itisEmpty(): checks if the stack is emptysize(): returns the size of the stackclear(): clears the stack of all elements
We then create a new instance of the Stack class called myStack and add some elements to it using the push() method. We use the peek() method to get the top element without removing it, the pop() method to remove and return the top element, and the size() method to get the current size of the stack.
Finally, we log the results to the console using console.log().
