Hi guys, this is a homework assignment. Right now, I'm thinking that my solution should probably work - but of course it doesn't and I cant spot the problem. I was hoping one of you would be kind enough to look it over and see where I'm going wrong. My first guess is that nothing is being added to the temp array that gets returned in the function - because nothing is printed out in the loop inside of main. Please help me find the logic problem causing this.
Thank you
Here is the problem:
Given two sorted lists L1 and L2 (here STL list's),
write a procedure to compute L1 ∩ L2 (the intersection of L1 and L2). Specifically,
write the following template function:
template<typename T>
list<T> listIntersection(const list<T>& L1, const list<T>& L2);
For example, if L1, L2 are (STL) list of int's, and L1 contains {2, 5, 7, 8, 10} and
L2 contains {5, 6, 10, 24}, the function returns a new/different list which contains{5, 10}.
IMPORTANT: Think about an EFFICIENT logic. Take advantage of the fact/assumption that
L1 and L2 are in the sorted order. You should be able to do this procedure by traversing
two lists exactly once (i.e., O(n) linear complexity).
Here is my solution:
Code:template<typename T> list<T> listIntersection(const list<T>& L1, const list<T>& L2){ //list to return list<T> temp; //iterators list<T>::const_iterator L1itr = L1.begin(); list<T>::const_iterator L2itr = L2.begin(); while(L1itr == L1.end() || L2itr == L2.end()){ //check to see if they're equal, add to our temp list if(*L1itr == *L2itr){ //add to temp temp.push_back(*L1itr); //advance iterators L1itr++; L2itr++; } if(*L1itr < *L2itr){ //advance L1 iterator L1itr++; } else{ //*L1itr > *L2itr //advance L2 iterator L2itr++; }//end if else if block }//end while return temp; }//end function here is the main() implementation:Code:#include <iostream> #include <list> using namespace std; template<typename T> list<T> listIntersection(const list<T>& L1, const list<T>& L2); int main(){ list<int> L1; L1.push_back(2); L1.push_back(5); L1.push_back(7); L1.push_back(8); L1.push_back(10); list<int> L2; L2.push_back(5); L2.push_back(6); L2.push_back(10); L2.push_back(24); system("pause"); list<int> t = listIntersection(L1, L2); for(list<int>::iterator i = t.begin(); i != t.end(); i++){ cout << *i; } system("pause"); return 0; }