I appreciate it everyone! I figured out the intersection last night but now my problem is I believe the call of the intersection. My program freezes up so I included the whole code. The union works with no problem when I run the whole program. Any help would be appreciated. Please do not mind the extra variables in int main().
Code:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
class List
{ protected:
Node* head;
public:
List()
{
head=NULL;
}
~List();
void Inserthead(int x);
int search(int x);
void display();
};
void List::Inserthead(int x)
{
Node* newnode = new Node;
newnode->data = x;
if (head == NULL)
{
head=newnode;
newnode->next = NULL;
}
else
{
newnode->next = head;
head = newnode;
}
}
void List::display()
{
Node* currnode=head;
while(currnode!=NULL)
{
cout<<currnode->data<<" ";
currnode=currnode->next;
}
}
int List::search(int x)
{
Node* currnode;
int count =0 ;
for (currnode = head; currnode != NULL; currnode = currnode->next)
{
if (currnode->data == x)
{
return count;
}
count++;
}
return -1;
}
List::~List()
{
Node* currnode=head;
Node* nextnode=NULL;
while(currnode)
{
nextnode->next=currnode->next;
delete currnode;
currnode=nextnode;
}
}
class Set:public List
{
public:
void insnew(int x)
{ int copy;
copy=search(x);
if(copy==-1)
Inserthead(x);
}
void Union(Set& a,Set& b)
{
Node* p;
for(p=a.head;p!=NULL;p=p->next)
{
insnew(p->data);
}
for( p= b.head;p!= NULL;p = p->next)
{
insnew(p->data);
}
}
void intersection(Set& a,Set& b)
{
Node* p;
Node* q;
for( p = a.head; p != NULL; p = p->next)
{
for( q = b.head; q != NULL; q = q->next)
{
if (p->data == q->data)
{
insnew(p->data);
}
}
}
}
};
int main()
{
Set setA, setB, setUnion, setIntersection;
int i,m,n,a,b;
cout<<"Enter no of elements in set A: ";
cin>>n;
cout<<"Enter elements of A: ";
for(i=0;i<n;i++)
{
cin>>a;
setA.insnew(a);
}
cout<<"Enter no of elements in set B: ";
cin>>m;
cout<<"Enter elements of B: ";
for(i=0;i<m;i++)
{
cin>>b;
setB.insnew(b);
}
setUnion.Union(setA, setB);
cout << "Contents of setA union setB: ";
setUnion.display();
setIntersection.intersection(setA, setB);
setIntersection.display();
cout << "Contents of setA intersection setB: ";
return 0;
}