I would like to ask about the time complexity of my function. Below is my function written in C++.
void List::swap(List& other)
{
List temp;
Iterator r = begin();
Iterator i = other.begin();
while(!i.equals(other.end()))
{
temp.push_back(i.position->data);
i = other.erase(i);
}
while(!r.equals(end()))
{
other.push_back(r.position->data);
r = erase(r);
}
r = temp.begin();
for(r; !r.equals(temp.end()); r.next())
{
push_back(r.position->data);
}
}
The function purpose is swapping elements of two linked lists. The exercise requires this function to be executed in O(1) time. Because I used 3 loops, I wasn’t sure how exactly to count the time complexity for mine function.
Since you are talking about the Big Oh notation , the complexity would be the max(complexity of loop1, complexity of loop2, complexity of loop3) . Since you are using 3 loops the complexity will definitely not be O(1).
Hint: Since these are linked lists, you only need to swap the head pointers.