How do you find length of a Singly Linked list

本文探讨了两种计算单链表长度的方法:迭代法和递归法。迭代法通过遍历链表并计数来确定长度;递归法则利用递归调用直至到达链表尾部。这两种方法为Java开发者提供了不同的视角来理解数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Here is one of the classical questions asked to me on an interview with multinational Investment bank after that this question asked to me on several times in other interviews also . what makes this question interesting is that java developers are not that great with data structure relative to C++ developer which is obvious because of fundamental difference between this two language.C++ is more of system programming language while java is more on application programming , also rich set of java API allows programmer to skip this kind of basic programming techniques.


anyway lets come back to the question , everybody knows that Linked lists is last element will point to "null" element , so first answer would most of the times would be "I will use a counter and increment till we reach the end of the element" e.g.


Iterative Solutions


public int length(){
int count=0;
Node current = this.head;

while(current != null){
count++;
current=current. next()
}
return count;
}

If you answer this question without any difficulty most interviewer will ask you to write a "recursive" solution for this just to check how you deal with recursion if your first answer would have been recursive they will ask you to write an "iterative solution" as shown above.

Recursive Solution:

public int length(Node current){
if(current == null) //base case
return 0;

return 1+length(current.next());
}


Read more: http://javarevisited.blogspot.com/2010/10/how-do-you-find-length-of-singly-linked.html#ixzz2khZ1aahc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值