The top
is the pointer that tracks the position where new elements should be stored. If the top is equal to -1
(which is its starting point), then the stack is empty. If the top
is equal to MAXSIZE
, it means the stack is full. The size of this specific stack is 9
.
Now check out these below methods:
1class Stack {
2 // Array is used to implement stack
3 constructor() {
4 this.items = [];
5 }
6
7 // Functions we'll need
8 push(val) {
9 // Push element into the items array
10 this.items.push(val);
11 }
12 pop() {
13 // Return top most element in the stack
14 // and remove it from the stack
15 if (!this.items.length) return "The stack has an underflow!";
16 return this.items.pop();
17 }
18 // peek()
19 // getSize()
20 // print()
21}