I am practicing data structures on JavaScript, and wrote a stack based linked list. However, three of my methods pop() peek() and toString() are faulty because they return undefined values, whereas I would like them to return the numerical values.
The rest of the stack methods are working fine! Could this be a scoping issue? Thank you for your time and help.
Updated working code is below after the comment suggestions!
class Node {
/* Creates a node with the given element and next node */
constructor(e, n) {
this.data = e;
this.next = n;
}
}
class LinkedStack {
/* Creates an empty stack */
constructor() {
this.top = null;
this.size = 0;
}
push = (elem) => {
let v = new Node(elem, this.top);
this.top = v;
this.size++;
}
length = () => {
return this.size;
}
isEmpty = () => {
return this.size === 0;
}
peek = () => {
if (this.isEmpty()) {
console.log("Empty Stack");
}
return this.top.data;
}
pop = () => {
if (this.isEmpty()) {
console.log("Empty Stack");
}
const temp = this.top.data;
this.top = this.top.next;
this.size--;
return temp;
}
toString = () => {
let s = "[";
let cur = null;
if (this.length() > 0) {
cur = this.top;
s += cur.data;
}
if (this.length() > 1) {
for (let i = 1; i <= this.length() - 1; i++) {
cur = cur.next;
s += ", " + cur.data;
}
s += "]";
return s;
}
}
}
let stack = new LinkedStack();
stack.push(9);
console.log(stack.pop() + " was popped"); // undefined, but stack size decreases
stack.push(12);
stack.push(15);
console.log("Is Stack Empty? " + stack.isEmpty());
console.log("Stack Length: " + stack.length());
console.log("Top value: " + stack.peek());
console.log("Stack Content: " + stack.toString()); // Stack content [15, undefined]