FAQ: Learn Linked Lists: JavaScript - Linked List Review

This community-built FAQ covers the “Linked List Review” exercise from the lesson “Learn Linked Lists: JavaScript”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Pass the Technical Interview with JavaScript

FAQs on the exercise Linked List Review

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Feel free to comment or look for improvements.

1st pass at LinkedList with following

properties:
this.head = null;
this.tail = null;

Methods:
addToHead()
addToTail()
removeHead()
removeTail()
traverseNode()
checkIfNodeExists()
insertNode()
removeNode()
printList()

Node modified as well:

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

  setNextNode(node) {
    if (!(node instanceof Node || node === null)) {
      throw new Error('Next node must be a member of the Node class');
    }
    this.next = node;
  }

  getNextNode() {
    return this.next;
  }
}

module.exports = Node;

LinkedList

const Node = require('./Node');

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  addToHead(data) {
    const newHead = new Node(data);
    const currentHead = this.head;
    this.head = newHead;
    if (currentHead) {
      this.head.setNextNode(currentHead);
    }
  }

  addToTail(data) {
    let tail = this.head;
    if (!tail) {
      this.head = new Node(data);
    } else {
      while (tail.getNextNode() !== null) {
        tail = tail.getNextNode();
      }
      tail.setNextNode(new Node(data));
      this.tail = tail;
    }
  }

  removeHead() {
    const removedHead = this.head;
    if (!removedHead) {
      return;
    }
    this.head = removedHead.getNextNode();
    return removedHead.data;
  }

  removeTail() {
    if (this.head === null) {
      return null;
    }

    let currentNode = this.head;
    let prevNode = this.head;
    while (currentNode.getNextNode() !== null) {
      prevNode = currentNode;
      currentNode = currentNode.getNextNode();
    }
    this.tail = prevNode;
    prevNode.setNextNode(null);
  }

  traverseNode(data) {
    if (this.head === null) {
      return null;
    }

    let currentNode = this.head;
    let prevNode = this.head;
    while (currentNode !== null && currentNode.data !== data) {
      prevNode = currentNode;
      currentNode = currentNode.getNextNode();
    }

    if (currentNode === null) {
      return null;
    }

    return {
      prevNode,
      currentNode,
    };
  }

  checkIfNodeExists(data) {
    return this.traverseNode(data) !== null ? true : false;
  }

  insertNode(prevNodeData, data) {
    if (this.head === null) {
      addToHead(data);
      return;
    }
    const newNode = new Node(data);
    // if we do .prevNode then we get node before
    // previous node we want to insert after
    if (this.checkIfNodeExists(prevNodeData)) {
      let prevNode = this.traverseNode(prevNodeData).currentNode;
      let nextNode = prevNode.getNextNode();
      // prev -> newNode -> nextNode
      prevNode.setNextNode(newNode);
      newNode.setNextNode(nextNode);
    } else {
      throw new Error('Node not found');
    }
  }

  removeNode(data) {
    if (this.head.data === data) {
      this.removeHead();
      return;
    }

    if (this.tail.data === data) {
      this.removeTail();
      return;
    }

    let prevNode = this.traverseNode(data).prevNode;
    let currentNode = this.traverseNode(data).currentNode;
    let removedNode = currentNode;
    prevNode.setNextNode(currentNode.getNextNode());

    return removedNode;
  }

  printList() {
    let currentNode = this.head;
    let output = '<head> ';
    while (currentNode !== null) {
      output += currentNode.data + ' ';
      currentNode = currentNode.getNextNode();
    }
    output += '<tail>';
    console.log(output);
  }
}

module.exports = LinkedList;

A great source for learning about Data Structures and Algorithms in depth:

As I understand LinkedList is a subclass of Node. Why don’t we use “extends” when creating LinkedList in this particular case?

Created a method to remove a node from the link list based on data value:

removeNode(data) {
    let previousNode = null;
    let currentNode = this.head;
    let nextNode = currentNode.getNextNode();
    if (currentNode) {
      while (currentNode) {
        if (currentNode.data !== data) {
          previousNode = currentNode;
          currentNode = nextNode;
          nextNode = currentNode.getNextNode();
        } else {
          if (previousNode) {
            previousNode.setNextNode(nextNode);
          } else {
            this.head = nextNode;
          }
          return;
        }
      }
    } else {
      return;
    }
  }

Hey could you explain how this method works please?

Sure, the method iterates through the linked list starting from the head.

  1. First I initialize variables for the starting point (currentNode as the head), previousNode (null since we’re at the head and there’s nothing before it), and the nextNode

  2. I then check to make sure the linked list isn’t empty (is there a head?) – if it is then return, to exit

  3. If the head exists, then while my currentNode isn’t null, I will compare the value of currentNode's data with the data argument

  4. If I get a match, I check to see if currentNode is still the head – if previousNode is null, then I’m at the head, and will set the new head to be nextNode – if previousNode is not null, then I set previousNode's next pointer to be nextNode – either way, the end result is that the node with the data match is now isolated, and I return to end the loop

  5. If I don’t get a match, then I “move” all three node pointers forward and check for a data match again until I either get a match (see step 4), or I reach the end of the linked list (currentNode becomes null), which breaks out of the while loop and ends

Hope this helps.

@rodrigogarcia2230329 when you use the “extends” keyword the new class inherits the methods of the parent class. In this case, Node and LinkedList don’t share any methods so I don’t believe LinkedList is a subclass of Node.