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

点点圈 提交于 2019-12-03 13:38:30

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

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.

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.

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