What is the longer code for the pop function in Javascript?

Our teacher asks us what is the longer code for the pop function.

These are his examples for shift and push:

this.shift = function() {

if (this.rootNode != undefined) {

thisrootNode.right; this.length--;

} else {

console.log("stack is already empty");

}

}

this.push = function(num) {

let currentNode = this.rootNode;

while(currentNode.right != undefined) {

currentNode = currentNode.right;

}

currentNode.right = new Node(num);

}

1 Answer

Relevance
  • Chris
    Lv 7
    7 months ago
    Favorite Answer

    Looks like a JS implementation of a binary tree class.

    pop() removes and returns an array's last element, so you need to find the rightmost child just like in this.push, then remove and return it.

    Like this:

    this.pop = function() {

    let currentNode = this.rootNode;

    while(currentNode.right != undefined) {

    currentNode = currentNode.right;

    }

    var lastNode = currentNode; // store

    currentNode.parentNode.right = null; // remove from tree

    return lastNode; // return

    }

    • ...Show all comments
    • Chris
      Lv 7
      7 months agoReport

      I was guessing, you need the correct property. It's also possible that the nodes don't have a "parent" property, in that case you need to change the loop so it stops one node short of the last.

    • Log in to reply to the answers
Still have questions? Get answers by asking now.