In stacks, first elements added to the stack are removed first, following the Last-In-First-Out principle (LIFO).
class Stack {
constructor()
{
this.items = [];
}
// The functions that need to be implemented
// push(item)
// pop()
// peek()
// isEmpty()
// length()
}
class Stack {
constructor()
{
this.items = [];
}
}
An element is pushed to the top of the stack with this operation.
push(element)
{
this.items.push(element);
}
An element at the top of a stack is removed using this operation.
pop()
{
this.items.pop();
}
In peek, the top element of a stack is returned without being removed.
peek()
{
this.items[this.items.length - 1];
}
Checks whether the stack is empty by using IsEmpty.
isEmpty()
{
this.items.length == 0;
}
let stack = [];
stack.push(1);
console.log(stack); // [1]
stack.push(2);
console.log(stack); // [1,2]
stack.push(3);
console.log(stack); // [1,2,3]
console.log(stack.pop()); // 3
console.log(stack); // [1,2];
//length
console.log(stack.length) // 2
//isEmpty
console.log(stack.length == 0) // false