Find intersection of two linked list.
Anonymous
People who ask such questions tend to like to see simple answers first and then keep asking you how to modify it to be faster. The simplest way is to traverse one list and for each element,. find out if it is in the other list. If so, add it to the returned set for an O(n^2) speed. You can then make it faster by copying one list into a set and then traversing the other list and testing each element for inclusion in the set and adding common elements into the returned set for O(n log n) speed. Finally, if the lists are sortable, start by sorting both lists. Then traverse them both at the same time by starting with a pointer to the first element in each list. Then in a loop while both pointers are not null, if they point to elements with the same value, add it to the returned set, and then advance the pointer to the element with the smallest value.for O(n) speed. I hope I got that right.
Check out your Company Bowl for anonymous work chats.