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

One way to find the sum of all nodes in a linked list is by recursively iterating through all the nodes and adding their values. Here is an example implementation in TypeScript:

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

function sumLinkedListRecursive(node: Node | null): number {
  if (!node) return 0;
  return node.value + sumLinkedListRecursive(node.next);
}
231 chars
9 lines

This function takes the head node of a linked list as a parameter, and returns the sum of all node values using recursion. The base case is when the node is null (i.e., we have reached the end of the list), in which case we return 0. Otherwise, we add the value of the current node to the sum of the remaining nodes, which we get by calling the sumLinkedListRecursive function on node.next.

Another way to find the sum of all nodes in a linked list is by iterating through all the nodes using a loop. Here is an example implementation in TypeScript:

index.ts
function sumLinkedListIterative(node: Node | null): number {
  let sum = 0;
  while (node) {
    sum += node.value;
    node = node.next;
  }
  return sum;
}
158 chars
9 lines

This function takes the head node of a linked list as a parameter, and returns the sum of all node values using iteration. We initialize a sum variable to 0, and then loop through all the nodes in the list using a while loop. For each node, we add its value to the sum variable, and move on to the next node by setting node to node.next. Once we reach the end of the list (i.e., node is null), we return the sum variable.

gistlibby LogSnag