There is two linked lists. They have common tail. I want to find latest element, which is the same in both lists.
For example,
List1
is 10->4->5->2->9->53->64->345->23
List2
is 10->4->5->2->8->53->64->345->23->43->53
I want to find 2.
We can iterate over list in O(n)
.
Is there a better way to find needed element, than in O(min(n, m))
?
node1 = list1head
node2 = list2head
ans = {error}
while(node1 && node2 && node1.data == node2.data)
ans = node1.data
node1 = node1.next
node2 = node2.next
end while
return ans
Cost = O(min(m, n))