find the length of a linked list in typescript

To find the length of a linked list in TypeScript, there are two commonly used approaches: iteration and recursion.

Iteration approach

In the iteration approach, we traverse the linked list from the head node to the tail node and keep a counter to count the number of nodes. Here's the TypeScript code for this approach:

index.ts
interface ListNode {
  value: any;
  next: ListNode | null;
}

function getLinkedListLength(head: ListNode): number {
  let length = 0;
  let currentNode = head;
  
  while (currentNode !== null) {
    length++;
    currentNode = currentNode.next;
  }
  
  return length;
}
274 chars
17 lines

Here, we define an interface ListNode to represent a node of the linked list. It has two properties: value to store the value of the node and next to point to the next node in the list. We also define a function getLinkedListLength that takes the head node of the list as an argument and returns the length of the list.

In the function, we initialize a counter length to 0 and a current node currentNode to the head of the list. We then use a while loop to traverse the list as long as currentNode is not null. Inside the loop, we increment length by 1 and update currentNode to the next node in the list. Finally, we return length.

Recursion approach

In the recursion approach, we traverse the linked list recursively and keep adding 1 to the length of the remaining list until the end is reached. Here's the TypeScript code for this approach:

index.ts
function getLinkedListLength(head: ListNode | null): number {
  if (head === null) {
    return 0;
  } else {
    return 1 + getLinkedListLength(head.next);
  }
}
163 chars
8 lines

This function takes the head node of the list as an argument and returns the length of the list. If the head node is null, we return 0. Otherwise, we add 1 to the length of the remaining list, which we get by calling getLinkedListLength recursively on the next node.

gistlibby LogSnag