There are auxiliary methods like top()
, or sometimes called peek()
, which are built-in functions that give you the value of what's on top of the stack. Here the top()
function calls top.data
which refers to the value inside of a node.
In the isEmpty()
method, top
is being compared to null. This is being done to check whether there is a value in the stack, or the stack is empty.
Attached is the full implementation of a stack using a linked list under the hood.
xxxxxxxxxx
57
stack.printStack(); // Should print 2, 1
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
​
class Stack {
constructor() {
this.top = null;
}
​
isEmpty() {
return this.top === null;
}
​
push(value) {
const newNode = new Node(value);
newNode.next = this.top;
this.top = newNode;
}
​
pop() {
if (this.isEmpty()) {
return null;
}
const removedNode = this.top;
this.top = this.top.next;
return removedNode.value;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment