#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}Lnode,*Linklist; //定义新的链表变量关键字
void CreatFromHead(Linklist L)//头插法创建链表
{
Lnode *s;
int c,flag=1;
L=(Linklist)malloc(sizeof(Lnode));
L->next=NULL;
while(flag)
{
scanf("%d",&c);//输入元素
if(c!=0)
{
s=(Linklist)malloc(sizeof(Lnode));
s->data=c;
s->next=L->next;
L->next=s;
}
else
flag=0;
}
}
void difference(Linklist LA,Linklist LB)//找出a,b集合的相同元素并删除 a中的这些元素
{
Linklist pre,p,r,q;
pre=LA,p=LA->next;//使pre永远指向p前面的结点
while(p!=NULL)
{
q=LB->next;
while(q!=NULL&&q->data!=p->data)
q=q->next;
if(q!=NULL)
{
r=p;
pre->next=p->next;
p=p->next;
free(r);
}
else
{
pre=p;
p=p->next ;
}
}
}
void Print(Linklist L) //输出修改后的a集合
{
while(L->next!=NULL)
{
L=L->next;
printf("%5d",L->data);
}
}
int main()
{
Linklist LA,LB;
printf("输入集合A的元素:\n");
CreatFromHead(LA);
printf("输入集合B的元素:\n");
CreatFromHead(LB);
difference(LA,LB);
Print(LA);
return 0;
}
修改如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}Lnode,*Linklist; //定义新的链表变量关键字
//函数需要返回链表头
Linklist CreatFromHead(Linklist L)//头插法创建链表
{
Lnode *s,*t;
int c,flag=1;
L=(Linklist)malloc(sizeof(Lnode));
L->next=NULL;
t = L;
while(flag)
{
scanf("%d",&c);//输入元素
if(c!=0)
{
s=(Linklist)malloc(sizeof(Lnode));
s->data=c;
//修改
s->next = 0;
t->next = s;
t = s;
//s->next=L->next;
//L->next=s;
}
else
flag=0;
}
return L;
}
//函数需要返回链表头
Linklist difference(Linklist LA,Linklist LB)//找出a,b集合的相同元素并删除 a中的这些元素
{
Linklist pre,p,r,q;
pre=LA,p=LA->next;//使pre永远指向p前面的结点
while(p!=NULL)
{
q=LB->next;
while(q!=NULL&&q->data!=p->data)
q=q->next;
if(q!=NULL)
{
r=p;
pre->next=p->next;
p=p->next;
free(r);
}
else
{
pre=p;
p=p->next ;
}
}
return LA;
}
void Print(Linklist L) //输出修改后的a集合
{
while(L->next!=NULL)
{
L=L->next;
printf("%5d",L->data);
}
}
int main()
{
Linklist LA = 0,LB = 0;
printf("输入集合A的元素:\n");
LA = CreatFromHead(LA);
printf("输入集合B的元素:\n");
LB = CreatFromHead(LB);
LA = difference(LA,LB);
Print(LA);
return 0;
}