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

*爱你&永不变心* 提交于 2019-12-12 07:59:24

问题


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?


回答1:


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




回答2:


If you are doing allocation dynamically with something like malloc then there is no way other than updating a counter each time you insert/delete. If you're not doing allocation dynamically then you probably haven't implemented a linked list.




回答3:


What these other guys are saying is totally right. How can you know how many items are in something before you look at them?

You're going to need to maintain a count, and increment/decrement it on inserts/deletes. It's the (most|only) reliable way.




回答4:


Add a counter to your struct and make the linked list circular instead of singly. Instead of traversing through the entire list just traverse to the initial node's prev node.



来源:https://stackoverflow.com/questions/6368813/how-to-count-the-number-of-nodes-in-a-linked-list-without-traversing-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!