Here's how you can calculate the average of all the nodes in a linked list in TypeScript:
index.ts931 chars54 lines
In the Node
class, we define the value
and next
properties. In the LinkedList
class, we first define the head
property and set it to null. The add
method is used to add nodes to the list. The getAverage
method calculates the sum of all the nodes and then divides it by the total count of nodes to get the average. The method returns 0
if the count is 0
.
We then create an instance of the LinkedList
class and add some nodes to it. Finally, we call the getAverage
method and log the result to the console, which outputs the expected result of 10
.
gistlibby LogSnag