DEV Community

Discussion on: Solution: Remove Nth Node From End of List

Collapse
 
eugbyte profile image
Eugene

can you explain this line if (!fast) return head.next?

Collapse
 
seanpgallivan profile image
seanpgallivan

Sure. The bang operator (!) returns the opposite boolean value of the thing to which it's attached. In this case, fast is either a node reference, which evaluates as truthy, or it's null, which is falsy.

So !fast returns true if fast is null, but returns false if fast is a list node reference. Basically, it's a faster way of writing if (fast === null) return head.next.

This line deals with an edge case where, if we go forward n nodes and find the end of the list, it means that the nth node from the end is actually the very first node. Since the rest of the code assumes that we'll be finding nodes on either side of the target node which can be stitched together, this can cause a problem, as there is no node prior to the start of the list.

So the easiest thing to do is just to "remove" it by simply returning the second node of the list as the head of our answer list.