We have to check if two given linked lists contain the same data. Order in this case does not matter, meaning that {1,3,2} and {2,1,3}are same. I think that we should introduce a new variable counter=0 and perform the following procedure:
while(node1->next!=NULL)
{
int value=node1->value;
if(contains(node2,value)){
counter++;
}
node1=node1->next;
if(counter== number of elements in node 1)
return true;
else return false;
}
Another method is to sort both lists and compare node by node. Which one is optimal? In the first case it takes O(n^2) operations, while in the second case like Nlog(N)+O(N), (if we use merge sort). Am I right in my thinking? Or is there another optimal method?
Out of the two methods you posted, 2nd is better. But I would suggest you to
hashing.Hash the 1st linked list first.
Check the 2nd list while hashing it.
This way, it can be done in O(n) time in total.