#include<iostream>
using namespace std;
#define ElemType int
template <class DT>
struct LNode
{
DT data;
LNode *next;
};
template<class DT>
bool InitList(LNode<DT>* &L)
{
L= new LNode< DT>;
if(!L) exit(1);
L-> next= NULL;
return true;
}
template<class DT>
bool CreateList(LNode<DT>* &L,int n)
{
LNode<DT> *p,*s;
p=L;
cout<<"依次输入"<<n<<"个数据元素:"<<endl;
for(int i=1; i<=n;i++)
{
s=new LNode<DT>;
if (!s)
return false;
cin>>s->data;
s->next=p->next;
p->next=s;
p=s;
}
return true;
}
template<class DT>
bool GetElem_i(LNode<DT>* L,int i,DT &e)
{
LNode<DT> *p;
p=L->next;
int j=1;
while(p&&j<i)
{
p=p->next;j++;
}
if(!p ||j>i )
return false;
else
{
e=p->data;
return true;
}
}
template<class DT>
int LocateElem_e(LNode<DT>* L,DT e)
{
LNode<DT> *p;
p=L->next;
int j=1;
while(p && p->data!=e)
{
p=p->next;
j++;
}
if(p==NULL)
return 0;
else
return j;
}
template<class DT>
DeleteELem_i(LNode<DT>* &L,int i)
{
LNode<DT> *p,*q;
p=L;
int j=0;
while(p->next && j<i-1)
{
p=p->next; //
j++;
}
if(!p->next||j>i-1)
return false;
else
{
q=p->next;
p->next=q->next;
delete q;
return true;
}
}
template<class DT>
void DispList (LNode<DT>* L)
{
LNode<DT> *p;
p=L->next;
while(p)
{
cout<<p->data<<"\t";
p=p->next;
}
cout<<endl;
}
template<class DT>
void Intersection(LNode<DT>LA, LNode<DT>LB)
{
DT e;
for (int i = 1; i <= LA.length; i++)
{
GetElem_i(LA, i, e);
if (LocateElem_e(LB, e)==0)
{
DeleteELem_i(LA,i);
i--;
}
}
}
int main(void) {
int i;
LNode<int> LA,LB;
InitList(&LA);
cout << "请输入LA的元素个数:" << endl;
cin >> i;
CreateList(&LA,i);
InitList(&LB);
cout << "请输入LB的元素个数:" << endl;
cin >> i;
CreateList(&LB, i);
cout << "LA和LB的交集为:" << endl;
Intersection(LA, LB);
DispList(&LA);
return 0;
}
刚学数据结构,代码不知道怎么改,还是我思路本身有问题?
A∩B,检测A中每个节点,是不是在B中出现,没出现的就删了