集合的运算

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

#define len sizeof(struct order)

#include<string.h>

struct order

{char num;

struct order *next;

};

void main()

{int i,j;

char p1[30],p2[30];

struct order *b,*bpre,*bhead,*a,*apre,*ahead,*p;

printf("\nenter the first chars :");

gets(p1);

order(p1,strlen(p1));

printf("\nenter the second chars :");

gets(p2);

order(p2,strlen(p2));

a=apre=(struct order*)malloc(len);

for(i=0;i<strlen(p1);i++)

if((p1[i]>='a')&&(p1[i]<='z'))

break;

a->num=p1[i];

ahead=a;

for(j=i+1;j<=strlen(p1);j++)

{ a=(struct order*)malloc(len);

while(p1[j-1]==p1[j])

j=j+1;

a->num=p1[j];

apre->next=a;

apre=a;

}

a->next=0;

a=ahead;

b=bpre=(struct order*)malloc(len);

for(i=0;i<strlen(p2);i++)

if((p2[i]>='a')&&(p2[i]<='z'))

break;

b->num=p2[i];

bhead=b;

for(j=i+1;j<=strlen(p2);j++)

{ b=(struct order*)malloc(len);

while(p2[j-1]==p2[j])

j=j+1;

b->num=p2[j];

bpre->next=b;

bpre=b;

}

b->next=0;

b=bhead;

printf("the p1Up2 is:");

while(a->next!=0&&b->next!=0) //判断并集 注意指针的移动

{if(a->num==b->num)

{ printf("%c",a->num);

a=a->next;

b=b->next;}

if(a->num<b->num)

{ printf("%c",a->num);

a=a->next;}

if(a->num>b->num)

{ printf("%c",b->num);

b=b->next;}

}

while(a->next!=0) //是否还有a,b剩余的情况

{ printf("%c",a->num);

a=a->next;}

while(b->next!=0)

{ printf("%c",b->num);

b=b->next;}

a=ahead;b=bhead;

printf("\nthe p1%cp2 is:",239); //交集

while(a->next!=0&&b->next!=0)

{ if(a->num==b->num)

{ printf("%c",a->num);

a=a->next;

b=b->next;

}

if(a->num<b->num)

a=a->next;

if(a->num>b->num)

b=b->next;

}

a=ahead;b=bhead;

printf("\nthe p1-p2 is:");

while(a->next!=0&&b->next!=0) //注意a指针的移动

{ if(a->num==b->num)

{ p=a;

a=a->next;

b=b->next;

if(p==ahead)

ahead=a;

else

apre->next=a;

free(p);

}

if(a->num<b->num)

{ apre=a;

a=a->next;

}

if(a->num>b->num)

b=b->next;

}

a=ahead;

while(a->next!=0)

{ printf("%c",a->num);

a=a->next;

}

a=ahead;b=bhead;

getch();

}

order(char a[15],int n) //为字符串排序

{ int i,j,k;

char t;

for(i=0;i<n-1;i++)

{ k=i;

for(j=i+1;j<n;j++)

if(a[j]<=a[k]) k=j;

t=a[k];a[k]=a[i];a[i]=t;

}

}



总结:将字符串排序,相同的去掉,然后入链表

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航