如何计算一个链表节点的数量,而不穿越了吗? [英] How to count the number of nodes in a linked list without traversing it?

查看:223
本文介绍了如何计算一个链表节点的数量,而不穿越了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人问我在接受采访时如何计算一个链表节点的数量,而不遍历目录?有什么办法来实现这一目标?

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?

推荐答案

我能想到的唯一的办法就是增加它每次的添加的或增加节点数目的计数器插入的方法被调用,当删除的被调用的递减。你不能让有关内存的假设,因为被占用,是一个链表,你不能保证所有节点将在相同的内存块(实际上,这是非常难以琢磨的)。

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

这篇关于如何计算一个链表节点的数量,而不穿越了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆