I'm trying to implement a simple Stack in javascript (I know it can be implemented with a simple array, but that's not my point.) So here's my design:
pop(): remove and return the item from the top of the stack
push(item): add the item at the top of the stack
peek(): return the item from the top of the stack
isEmpty(): return true if stack is empty
It'll have a top property that keeps track of the top element and here's my class definition:
class Stack {
constructor(data) {
this.data = data;
this.next = null;
this.top = Stack(data); // <- Here's my problem
}
pop() {
if(this.top == null) return new Error('Trying to pop, but the stack is empty.');
let item = this.top.data;
this.top = this.top.next;
return item;
}
push(data) {
let item = new Stack(data);
item.next = this.top;
this.top = item;
}
peek() {
if(this.top == null) return new Error('Peeking the stack, but the stack is empty.');
return this.top.data;
}
isEmpty() {
return top == null;
}
}
I want the top property to be a Stack element, however, as you can see, that'd throw me into an infinite loop. I could just set top as an object that has data, next, and top. But is that the only way? Perhaps I can have a member function that generates the top property when initializing the class? But still, I'll eventually have to set that to an object instead of a Stack object.
Any suggestion?