Well, I think the answer depend on what are really these 'nodes'. If we consider them as objects holding the information on the next node - which forms the linkedlist - as well as their own data , then Varalu's solution would work. Indeed, if two nodes from the two linked lists are equal, it means they point to the same 'next node' object, which in turn will point to the same 'next node', etc. In this case,
if the two linked list have a common node at some point,
then the end of the two linked lists will be equal too. This, in turn, means that ,
if the two linked list have a common node,
then this common node will be at the same position from the end in the two linked lists. Removing the extra nodes in the longest list and starting comparing from here thus work, in o(n).
For the case where elements of the list do not contain the reference to the 'next node' but only their value (such that you can have 1->2 in one list and 1->3 in the other), then we can think of a o(n) solution.
Suppose there is a way to traverse the list in the reverse order, beginning by the end and navigating to the previous (if the data structure does not enable it, then converting it into a data structurewhich enables it can be done in o(n) anyway). In this case, the algo would be :
0. mergingNode initialised to 'no merging node found (yet)'
1. currentNode from both lists = last node from both lists
2. compare both currentNodes
2.1 if they are different, return mergingNode
2.2 if they are equal :
2.2.1 mergingNode = currentNode
2.2.2 currentNodes from both list = previous element from both list (return mergingNode if one of the nodes does not exist - one list is finished)
2.2.3 go back to 2.
3. if we are here, the two lists are totally equal
This is an o(n) algorithm for that.
Reply