資源簡介
集合的交、并和差運(yùn)算的實(shí)現(xiàn)。用有序單鏈表表示集合,實(shí)現(xiàn)集合的交、并和差運(yùn)算。對集合中的元素,用有序單鏈表進(jìn)行存儲。實(shí)現(xiàn)交、并、差運(yùn)算時(shí),不另外申請存儲空間。充分利用單鏈表的有序性,算法有較好的時(shí)間性能。
代碼片段和文件信息
#include?
using?namespace?std;?
typedef?struct?Node{?
char?data;?
Node?*next;?
}Node*linkList;?
#define?SIZE?sizeof(Node)?
#define?FALSE?0?
#define?TRUE?1?
//初始化集合?
void?InitlinkList(linkList?Head)?
{?
char?ch;Node?*p=Head;?
Head->next=NULL;?
Head->data=‘\0‘;?
cin>>ch;?
while(ch!=‘#‘)?
{?
Node?*newNode=(Node*)malloc(SIZE);?
newNode->data=ch;?
p->next=newNode;?
p=p->next;?
cin>>ch;?
}?
p->next=NULL;?
}?
//將表中的位置排序?
?void?Sort(linkList?head)
??{
???Node?*p=head->next*q*r;
????if(p!=NULL)????????????????
??????{
????????r=p->next;
????????p->next=NULL;
????????p=r;
????????while(p!=NULL)
??????????{
????????????r=p->next;
????????????q=head;
????????????while(q->next!=NULL&&q->next->data>p->data)
???????????????q=q->next;???????????????//在有序表中找插入*p的前驅(qū)結(jié)點(diǎn)*q
????????????p->next=q->next;????????//將*p插到*q之后
????????????q->next=p;
????????????p=r;
??????????}
??????}
??}
??
??
//檢查p1或p2所指向數(shù)據(jù)結(jié)點(diǎn)該不該加入到Head為起始的集合中^-^有點(diǎn)拗口,表達(dá)不是很好?
int?Check(char?chlinkList?Head)?
{?
Node?*temp=Head->next;?
int?flag=TRUE;?
while(temp!=NULL)?
{?
if(temp->data==ch){//不需要將數(shù)據(jù)插入?
flag=FALSE;?
return?flag;?
}?
temp=temp->next;?
}?
return?flag;?
}?
//合并兩個(gè)集合?
linkList?Merge(linkList?Head1linkList?Head2)?
{?
linkList?Head=(Node*)malloc(SIZE);?
Head->data=‘\0‘;Head->next=NULL;?
Node?*p1=Head1->next;?
Node?*p2=Head2->next;?
Node?*p=Head;?
while(p1!=NULL&&p2!=NULL)?
{?
if(p1->data==p2->data)?
{?
if(Check(p1->dataHead)==TRUE)?
{?
Node?*newNode=(Node*)malloc(SIZE);?
newNode->data=p1->data;?
p->next=newNode;?
p=newNode;?
p->next=NULL;?
}?
}?
else?
{?
if(Check(p1->dataHead)==TRUE)?
{?
Node?*newNode=(Node*)malloc(SIZE);?
newNode->data=p1->data;?
p->next=newNode;?
p=newNode;?
p->next=NULL;?
}?
if(Check(p2->dataHead)==TRUE)?
{?
Node?*newNode=(Node*)malloc(SIZE);?
newNode->data=p2->data;?
p->next=newNode;?
p=newNode;?
p->next=NULL;?
}?
}?
p1=p1->next;?
p2=p2->next;?
}?
while(p1!=NULL)?
{?
if(Check(p1->dataHead)==TRUE)?
{?
Node?*newNode=(Node*)malloc(SIZE);?
newNode->data=p1->data;?
p->next=new
評論
共有 條評論