Search code examples
javascriptdata-structureslinked-liststack

Javascript Stack Linked list implementation


I am confused in this javascript linked list implementation, in the pop() function how can we do this.top.next. The next attribute is inside node class so how can we access it with a stack class attribute top?

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = null;
  }

  peek() {
    return this.top;
  }
  push(value) {
    const New_node = new Node(value);
     if (this.top === null) {
       this.top = New_node;
      this.bottom = New_node;
    } else {
      New_node.next = this.top;
      this.top = New_node;
    }
    this.length++;
    return this;
  }

  pop() {
    if (this.top === null) {
      return null;
    } else {
      this.top = this.top.next;
    }
    this.length--;
    return this;
}
const myStack = new Stack();
myStack.push("google");
myStack.push("facebook");
myStack.push("netflix");
myStack.pop();
console.log(myStack);

Solution

  • The next attribute is inside node class so how can we access it with a stack class attribute top?

    This is possible only when the stack is not empty. So initially, when this.top is null this would not work -- the reason why in the pop function this case is handled differently via the if statement.

    However, if the stack is not empty, then it means a push had been executed earlier on, and there we can see that this.top is assigned a node instance: New_node, which in turn was assigned new Node(value). So once that has been done, this.top is a node, and its node properties can be accessed with expressions like this.top.value and this.top.next.

    Also realise that value and next are "public" properties, and so there is no problem in accessing them from within another class. This is the default. Private properties have been a later addition to the JavaScript language, and have distinct names (hash-prefix).