Implementing Stacks & Queues
Why is tracking the 'top' index separately beneficial in this Stack implementation?
class Stack {
constructor() {
this.items = [];
this.top = -1;
}
push(element) {
this.top++;
this.items[this.top] = element;
}
pop() {
if (this.isEmpty()) return null;
const element = this.items[this.top];
delete this.items[this.top];
this.top--;
return element;
}
}