I have the task to code a method that return the length of a self-made linked list. The method must be in constant time O(1). My idea was to increment the counter by 1 always that a node in a linked list isn't null and not mess with the size of the list at all to avoid O(n).
My code:
public int getLength() {
// TODO Code hier einfügen
if (headNode == null) {
return 0;
}
int count = 0;
while (headNode != null)
{
count++;
headNode = headNode.next;
}
return count;
}
Is my code in constant time O(1)? If not how would you create a length method for a linked list in O(1)?
You code is O(n). You cannot get the length of a linked list in O(1) if it is already crated and you have to traverse it all. To get the length in O(1) what you can do is to keep a variable that will increment whenever a node is inserted in the list and decrement whenever a node is deleted from the list.
To know the complexity of any code you have to look at the loops. Let's say the size of the list is n. If there is a loop in the code that goes from 1 to n then the complexity is O(n), similarly if there is another nested loop inside the first loop that also goes from 1 to n then the complexity is O(n^2). If there is no loop in the code that means its complexity is O(1).
I hope that answers your question.
Your code is O(n) since you are traversing all the nodes of the linked list atleast once. To address second part of your question, there are two ways it can be done:
Hope this helps.. Happy Coding:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.