简体   繁体   English

在单链表中查找节点的时间复杂度

[英]Finding a node in singly linked list time complexity

I have this question in my DSA Course Mid-term test: 我的DSA课程中期考试中有这个问题:

Consider a Single Linked List contains N nodes (N > 8), a method f1() is designed to find the 8th node from beginning, and method f2() is designed to find the 8th node from end. 考虑单个链表包含N个节点(N> 8),方法f1()设计为从头开始查找第8个节点,方法f2()设计为从头开始查找第8个节点。 Which is the time complexity of f1() and f2()? f1()和f2()的时间复杂度是多少?

Select one: 选择一个:

a. 一种。 O(N) and O(N) O(N)和O(N)

b. b。 O(1) and O(1) O(1)和O(1)

c. C。 O(1) and O(N) O(1)和O(N)

d. d。 O(N) and O(1) O(N)和O(1)

The correct answer given is c. 给出的正确答案是c。 O(1) and O(N). O(1)和O(N)。 However I think that the correct answer is a. 但是我认为正确答案是。 I know if N = 8 it will take O(1) time to find the 8th node from the beginning (just return the tail node) but in this case N > 8. Could any one explain this for me please? 我知道N = 8会花O(1)时间从头开始找到第8个节点(只是返回尾节点),但是在这种情况下N>8。请问有人可以帮我解释一下吗?

Thank you in advance for any help you can provide. 预先感谢您提供的任何帮助。

O(1) implies constant running time. O(1)表示运行时间恒定。 In other words, it doesn't depend on the input size. 换句话说,它不取决于输入大小。

When you apply that definition here, you can see that fetching the 8th element is always a constant operation irrespective of the input size. 当您在此处应用该定义时,您会看到,无论输入大小如何,获取第8个元素始终是恒定操作。 This is because, irrespective of the size of the input (ex:10,100,100..), the operation get(8) will always take the same time. 这是因为,不管输入的大小(例如:10,100,100 ..),操作get(8)总是花费相同的时间。 Also, since we know for sure that n > 8, there's no chance that trying to fetch the 8th element will result in going beyond the size of the input. 另外,由于我们肯定知道n> 8,所以尝试获取第8个元素将不会超出输入的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM