To find the length of a linked list in TypeScript, there are two commonly used approaches: iteration and recursion.
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.ts274 chars17 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
.
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.ts163 chars8 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