I'm trying to write a function that takes two linked lists and creates a third one with only the common elements.
It assumes the first list (the caller) has no dups, but it doesn't seem to be working. The program doesn't crash, it just hangs when it is supposed to display L3 (the third list)..everything else runs and is displayed fine.
template <typename T>
LList <T> LList <T>:: common (LList <T> &B) //common fct
{
Node <T> *hunter1 = Head;
Node <T> *hunter2 = B.Head;
Node <T> *newTerm;
int flag = 0;
LList C;
while (hunter1->link != NULL) //put all of list 1 into new list
{
newTerm = new Node <T>;
newTerm->link = NULL;
newTerm->data = hunter1->data;
C.append(newTerm);
hunter1 = hunter1->link;
}
while (hunter2->link != NULL) //traverse through 2nd list
{
hunter1 = Head; //reset hunter1 to Head of List 1
flag = 0; //assume we do not have a dup
while (hunter1->link != NULL) //traverse through 1st list
{
if (hunter2->data == hunter1->data) //if the item we are looking at in 2nd list
//is anywhere in the 1st
{
flag = 1; //raise the flag
}
}
if (flag == 0) //if flag was not raised
{
newTerm = new Node <T>; //get memory allocation for a newTerm
newTerm->data = hunter2->data; //put this data in it
newTerm->link = NULL; //mark the end null
C.append (newTerm); //add it to our new list
}
hunter2 = hunter2->link; //move hunter down
}
return C;
}
int main()
{
LList <int> L1, L2, L3; //Declaring a Linked List
cout << "You will create two linked lists.\nA third one will be created with only common elements\n\n\n";
L1.create();
cout << "\nList 1: ";
L1.display();
L2.create();
cout << "\nList 2: ";
L2.display();
L3 = L1.common(L2);
cout << "\nCommon List: ";
L3.display();
return 0;
}
I honestly think my algorithm should work.. I just tried another program using a similar function and my program is hanging again..something is causing it to hang..