代码如下:
复制代码
1
2
3
4
5
6
7
8
9public static int length(ListNode head) { int len = 0; while (head != null) { len++; head = head.next; } return len; }
这个代码看起来是正确的,但实际上问题很大,因为函数内部改变了传入的参数的值,参数是reference type, 这样会导致参数的值的变化。因此要记住:无论何时,不能修改传入的参数,如果需要用到,则新建一个空间复制参数,再进行操作:
复制代码
1
2
3
4
5
6
7
8
9
10public static int length(ListNode head) { ListNode cur = head; int len = 0; while (cur != null) { len++; cur = cur.next; } return len; }
最后
以上就是整齐往事最近收集整理的关于求LinkedList长度的全部内容,更多相关求LinkedList长度内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复