I have been asked in an interview how to count the number of nodes in a linked list without traversing the list? Is there any way to achieve this?
A linked list is a sequence of nodes that contain two fields: an integer value and a link to the next node. The last node is linked to a terminator used to signify the end of the list.
What is the number of comparisons required to search an element in a sorted linked list in the worst case? As per the answer key the correct answer is n. But i thought this way, in a sorted linked list, the search needn't move through all the elements.
The only way I can think of is to add a counter of the number of nodes which is incremented each time the add or insert methods are invoked, and decremented when delete is invoked. You cannot make assumptions about memory occupied because, being a linked list, you cannot guarantee that all nodes will be in the same memory block (indeed, this is highly improbable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With