C++差集

  • 格式:doc
  • 大小:28.00 KB
  • 文档页数:3

#include<stdio.h>
#include<malloc.h>
struct linknode
{
int data;
struct linknode *next;
};
struct linknode *create()//创建单链表
{
int d;
int i=1;
struct linknode *head,*s,*t;
head=NULL;
printf("建立一个单链表,data域数据已0结束:\n");
while(1)
{
printf("%d:",i);
scanf("%d",&d);
if(d==0)
break;
if(i==1)//建立第一个结点
{
head=(struct linknode *)malloc(sizeof(struct linknode)); head->data=d;
head->next=NULL;
t=head;
}
else//建立其余结点
{
s=(struct linknode *)malloc(sizeof(struct linknode));
s->data=d;
s->next=NULL;
t->next=s;
t=s;
}
i++;
}
return head;
}
void disp(struct linknode *head)//输出结点数据
{
struct linknode *p=head;
printf("输出一个单链表:\n");
if(p==NULL)
printf("空");
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
struct linknode *subs(struct linknode *ha,struct linknode *hb)
{
int flag=0;
struct linknode *r,*s,*pa,*pb,*head;
pa=ha,pb=hb;
s=(struct linknode *)malloc(sizeof(struct linknode));//哨兵结点s->next=NULL;
r=s;
head=s;
while(pa!=NULL)
{
flag=0;
for(pb=hb;pb!=NULL;pb=pb->next)//找到数据域相同的结点*/
if(pa->data==pb->data)
{
flag=1;//结点相同就跳出
break;
}
if(flag)//若结点相同就指向下一个结点即删除当前结点
{
pa=pa->next;
free(pa);
}
else//没有相同的结点就保留
{
r->next=pa;
r=pa;
pa=pa->next;
r->next=NULL;
}
}
head=s->next;
free(s);//释放哨兵结点
return head;
}
void main()
{
struct linknode *head_1,*head_2,*head_3;
head_1=create();
head_2=create();
head_3=subs(head_1,head_2);
printf("集合A,和集合相减后的结果为\n");
disp(head_3);
}。