Stacks
A stack is a data structure that follows the LIFO (last-in, first-out) principle, which means that the last element added to the stack will be the first one to be removed. A stack can be implemented using an array or a linked list. Stacks are used in many algorithms and applications, such as expression evaluation, backtracking, and parsing.
Here is an example of creating a stack using an array in JavaScript:
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
if (this.isEmpty()) {
return null;
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
In this example, the Stack class is defined with several methods, including push(), pop(), peek(), isEmpty(), size(), and clear(). The push() method adds a new item to the top of the stack, while the pop() method removes and returns the top item from the stack. The peek() method returns the top item from the stack without removing it. The isEmpty() method returns true if the stack is empty, and false otherwise. The size() method returns the number of items in the stack. The clear() method removes all items from the stack.
Here are some examples of how to use the Stack class:
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.size()); // Output: 3
console.log(stack.peek()); // Output: 3
console.log(stack.pop()); // Output: 3
console.log(stack.size()); // Output: 2
console.log(stack.isEmpty()); // Output: false
stack.clear();
console.log(stack.size()); // Output: 0
In this example, we create a new Stack object and add several items to it using the push() method. We then use the size(), peek(), pop(), and isEmpty() methods to access and manipulate the items in the stack, and the clear() method to remove all items from the stack.
Stacks can be used in a variety of applications, such as function call stacks, undo/redo functionality, and browser history.