find the average of all nodes in a linked list in typescript

Here's how you can calculate the average of all the nodes in a linked list in TypeScript:

index.ts
class Node {
  public value: number;
  public next: Node;
  constructor(value: number) {
    this.value = value;
    this.next = null;
  }
}

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

  public add(value: number): void {
    let node = new Node(value);
    if (!this.head) {
      this.head = node;
    } else {
      let current: Node = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = node;
    }
  }

  public getAverage(): number {
    let sum: number = 0;
    let count: number = 0;
    let current: Node = this.head;

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

    if (count === 0) {
      return 0;
    }

    return sum / count;
  }
}

// Example usage
let list = new LinkedList();
list.add(5);
list.add(10);
list.add(15);
console.log(list.getAverage()); // Output: 10
931 chars
54 lines

In the Node class, we define the value and next properties. In the LinkedList class, we first define the head property and set it to null. The add method is used to add nodes to the list. The getAverage method calculates the sum of all the nodes and then divides it by the total count of nodes to get the average. The method returns 0 if the count is 0.

We then create an instance of the LinkedList class and add some nodes to it. Finally, we call the getAverage method and log the result to the console, which outputs the expected result of 10.

gistlibby LogSnag