what does (!node.next) mean? Is it the same as node.next != null?
The !
is the negation operator, it negates the value placed in front of it.
for example !node.next
is the same as node.next == false
.
In this case, !node.next
will return true
if node.next
is a falsy value like false
or null
or undefined
.
In the if
statement of your code, it will return the current node's value if there's no next node linked to that node since, in linked lists, nodes contain a value and a link to the next node.
Also, I don't understand this line return (node.value > biggestValueInRest ? node.value : biggestValueInRest);
Does it mean that if node.value is greater than biggestValueInRest, then node.value = biggestValueInRest?
That's a ternary operator, it's like a shortened if
that returns a value.
return (node.value > biggestValueInRest ? node.value : biggestValueInRest);
would be the same as:
if (node.value > biggestValueInRest)
return node.value;
else
return biggestValueInRest;
The syntax of the ternary operator is basically:
"condition" ? "value to return if true" : "value to return if false"
And to fully answer your question.
I found a solution but don't really understand what they do.
The solution provided is a recursive one, it will call itself for each node in the linked lists until it reaches the final one ( the one which's node.next
is empty ), and once that's done, it will return the biggest value of each comparison from there.
Recursive functions aren't always a good practice, since their time complexity can escalate depending on how the developer implemented it.
In this case, it would be O(n) which means that it's linear, which is not too bad for a recursive function.
This means that the time the function will take to finish is affected in proportion to the number of items n
the linked list has.
So if it takes 1s per node, then 100 nodes would be 100s for the function to finish.