[英]Time complexity difference in Linkedlist implementation (Iterative VS Recursive)?
Does the time complexity change in these two implementation of getting the count of nodes in a Linkedlist ? 在获取Linkedlist中的节点数的这两个实现中,时间复杂度是否会发生变化?
private int getCountIterative() {
Node start = head;
int count = 0;
while (start != null)
{
count++;
start = start.next;
}
return count;
}
private int getCountRecursive(Node node) {
if (node == null)
return 0;
return 1 + getCountRecursive(node.next);
}
No, the time complexity won't change. 不,时间复杂度不会改变。
However the performance and overall run time will usually be worse for recursive solution because Java doesn't perform Tail Call Optimization . 但是,递归解决方案的性能和总体运行时间通常会更糟,因为Java不执行尾调用优化 。
To calculate the complexity of an operation (like a search or sort algorithm - or your example, the count), you need to identify the dominating operation . 要计算操作的复杂性(如搜索或排序算法 - 或您的示例,计数), 您需要确定主导操作 。
For searching and sorting, it's usually comparisons. 对于搜索和排序,通常是比较。 What is your dominating operation? 你的主导行动是什么? Let's assume it's node.next
, the lookup of the next node. 我们假设它是node.next
,查找下一个节点。
Then, both approaches have O(n) operations - so it's the same complexity. 然后,两种方法都有O(n)运算 - 因此它具有相同的复杂性。
Please be aware that this time complexity is a simplification. 请注意,这段时间的复杂性是一种简化。 There are factors ignored, like the overhead of function calls. 忽略了一些因素,比如函数调用的开销。 So, it's the same complexity, but that doesn't necessarily tell you which version is faster. 因此,它具有相同的复杂性,但这并不一定能告诉您哪个版本更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.