1.【附加题】–已知集合A和B的元素分别用不含头结点的单链表存储,
函数difference()用于求解集合A与B的差集,并将结果保存在集合A的单链表中。
例如,若集合A={5,10,20,15,25,30},集合B={5,15,35,25},完成计算后A={10,20,30}。
链表结点的结构类型定义如下:
struct node
{
int elem;
node* next;
};
请完成函数void difference(node** LA , node* LB);
#include<iostream>
using namespace std;
typedef struct Node
{
int elem;
Node* next;
Node(const int x)
:elem(x)
,next(NULL)
{}
}Node;
void difference(Node*& LA,Node*& LB)
{
//1.两个链表有一个为空,不用求差集
if (LA==NULL||LB==NULL)
{
return;
}
//2.两个链表都不为为空
else
{
Node* cur=LA;
Node* cur1=LB;
Node* del=NULL;
Node* delnext=NULL;
Node* prev=NULL;
while (cur&&cur1)
{
while(cur1)
{
if (cur->elem==cur1->elem)
{
if (cur->next==NULL)
{
del=cur;
cur=NULL;
//删除只有一个结点的链表的第一个结点
if (prev==NULL)
{
LA=NULL;
}
else
{
prev->next=NULL;
}
}
else
{
del=cur->next;
delnext=del->next;
std::swap(cur->elem,del->elem);
cur->next=delnext;
}
break;
}
cur1=cur1->next;
}
prev=cur;
if (del!=NULL)
{
delete del;
del=NULL;
}
else
{
cur=cur->next;
}
cur1=LB;
}
}
}
Node* CreatLinkList(int* arr,int sz)
{
Node* PHead=new Node(arr[0]);
Node* cur=PHead;
for (int i=1;i<sz;i++)
{
cur->next=new Node(arr[i]);
cur=cur->next;
}
return PHead;
}
void Printf(Node* LA)
{
if (LA==NULL)
{
return;
}
else
{
Node* cur=LA;
while (cur)
{
cout<<cur->elem<<"->";
cur=cur->next;
}
}
}
int main()
{
int A[]={5,10,20,15,25,30,66,99,23,77};
int B[]={5,15,35,25,77,65,54,66};
int sz1=sizeof(A)/sizeof(A[0]);
int sz2=sizeof(B)/sizeof(B[0]);
Node* LA=CreatLinkList(A,sz1);
Node* LB=CreatLinkList(B,sz2);
difference(LA,LB);
Printf(LA);
return 0;
}