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

Here is an example implementation of how to find the sum of all nodes in a linked list in JavaScript.

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

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

  add(data) {
    const node = new Node(data);

    if (!this.head) {
      this.head = node;
    } else {
      let current = this.head;

      while (current.next) {
        current = current.next;
      }

      current.next = node;
    }
  }

  sumNodes() {
    let sum = 0;
    let current = this.head;

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

    return sum;
  }
}

// Example usage
const list = new LinkedList();
list.add(3);
list.add(5);
list.add(1);
list.add(8);

console.log(list.sumNodes()); // Output: 17
714 chars
50 lines

In the sumNodes method, we iterate through each node while adding the data value of each node to the current sum. Once we reach the end of the linked list, we return the total sum.

gistlibby LogSnag