I wrote code for an enqueue method in a singly linked list and I'm wondering if anyone can tell me the Big O is for this code. I at first assumed it was O(n) because of the loop. However, the loop will always iterate a specific number of times depending on how many items are in the list. This makes me believe it's actually O(1). Am I wrong?
public Node<T> enqueue(T data){
Node<T> toQueue = new Node<>(data);
if (this.head == null) {
this.head = toQueue;
return toQueue;
}
Node<T> lastNode = this.head;
while(lastNode.next != null){
lastNode = lastNode.next;
}
lastNode.next = toQueue;
return toQueue;
}
Let's start from the following excerpt from the question:
This is a correct statement.
Please, note the dependency on the input size:
Therefore, the algorithm has the linear time complexity —
O(n).Linear time complexity
A slightly reformatted excerpt from the article: Time complexity: Linear_time - Wikipedia:
A slightly reformatted excerpt from the article: Big O notation: Orders of common functions - Wikipedia: let's refer to the corresponding row: