find the variance of all nodes in a linked list in javascript

To find the variance of all nodes in a linked list, we can follow these steps:

  1. Traverse through the linked list and find the mean value of all nodes.
  2. Traverse through the linked list again and calculate the variance for each node.
  3. Output the variance value for each node.

Here's the JavaScript code to achieve this:

index.tsx
class Node {
  constructor(value, next) {
    this.value = value;
    this.next = next;
  }
}

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

  addNode(value) {
    const newNode = new Node(value, null);

    if (!this.head) {
      this.head = newNode;
    } else {
      let currNode = this.head;
      while (currNode.next) {
        currNode = currNode.next;
      }
      currNode.next = newNode;
    }
  }

  findMean() {
    let sum = 0;
    let count = 0;
    let currNode = this.head;

    while (currNode) {
      sum += currNode.value;
      count++;
      currNode = currNode.next;
    }

    return sum / count;
  }

  findVariance() {
    let varianceList = [];
    const mean = this.findMean();
    let currNode = this.head;

    while (currNode) {
      varianceList.push(Math.pow(currNode.value - mean, 2));
      currNode = currNode.next;
    }

    currNode = this.head;
    let varianceCount = 0;

    while (currNode) {
      currNode.variance = varianceList[varianceCount];
      varianceCount++;
      currNode = currNode.next;
    }

    return this;
  }

  printList() {
    let currNode = this.head;
    while (currNode) {
      console.log(currNode.value + ": " + currNode.variance);
      currNode = currNode.next;
    }
  }
}

const linkedList = new LinkedList();
linkedList.addNode(1);
linkedList.addNode(2);
linkedList.addNode(3);
linkedList.addNode(4);
linkedList.addNode(5);

linkedList.findVariance().printList();
1465 chars
80 lines

In this code, we first create a Node class and a LinkedList class. We add a method findMean() to find the mean value of all nodes in the linked list. We then use this mean value to calculate the variance of each node in the findVariance() method.

Lastly, we have a printList() method to output the variance value for each node in the linked list.

gistlibby LogSnag