Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of nodes in a linked list without traversing it?

Tags:

c

linked-list

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?

like image 346
Amit Singh Tomar Avatar asked Jun 16 '11 08:06

Amit Singh Tomar


People also ask

How many nodes are in linked list?

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.

How many comparisons are required to count the number of nodes in the linked 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.


1 Answers

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).

like image 165
Baltasarq Avatar answered Sep 23 '22 04:09

Baltasarq