find the length of a linked list in javascript

To find the length of a linked list in JavaScript, we can traverse the entire list while keeping a count of nodes. Here's an example implementation:

index.tsx
function findLinkedListLength(head) {
  let count = 0;
  let currentNode = head;

  while (currentNode !== null) {
    count++;
    currentNode = currentNode.next;
  }

  return count;
}
187 chars
12 lines

Here, head represents the starting node of the linked list. We initialize count to 0 and currentNode to head. We then move currentNode to its next node in each iteration of the loop, incrementing count by 1 each time until we reach the end of the list (where currentNode is null). We then return the final value of count.

To use this function, you would call it with the head node of your linked list as an argument, like so:

index.tsx
const myList = {
  value: 3,
  next: {
    value: 7,
    next: {
      value: 10,
      next: null,
    },
  },
};

const length = findLinkedListLength(myList); // length will be 3
181 chars
13 lines

gistlibby LogSnag