两链表求交集
题目是:建立两个链表,A,B找交集,放入C中#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#define NULL 0 //宏定义NULL为0
#define SIZ sizeof(struct stu) //宏定义 SIZ为sizeof(struct stu)
struct stu //结构体
{
int num;
stu *next;
};
void main()
{
stu *Ha=NULL; stu *Hb=NULL; stu *Hc=NULL; //定义头指针
stu *r,*s;
struct stu *p,*q; //定义指针p,q
int x;
cout<<"in put A:"<<endl; //建立单链表A
cin>>x;
r=Ha;
for(;x;cin>>x)
{
s=(stu*) malloc(SIZ);
s->num=x;
if(Ha==NULL)
Ha=s;
else
r->next=s;
r=s;
}
if(r!=NULL)
r->next=NULL;
r=Ha; //输出单链表A
while(r!=NULL)
{
cout<<r->num<<" ";
r=r->next;
}
cout<<endl;
cout<<"in put B:"<<endl; //建立单链表B
cin>>x;
r=Hb;
for(;x;cin>>x)
{
s=(stu*)malloc(SIZ);
s->num=x;
if(Hb==NULL)
Hb=s;
else
r->next=s;
r=s;
}
if(r!=NULL)
r->next=NULL;
r=Hb;
while(r!=NULL) //输出单项链表B
{
cout<<r->num<<" ";
r=r->next;
}
cout<<endl;
p=Ha;q=Hb; //建立链表C
r=Hc;
for(;p&&q;p=p->next,q=q->next)
if(p->num=q->num)
{
s=(stu*) malloc(SIZ);
s->num=p->num;
if(Hc==NULL)
{
Hc=s;
r=Hc;
}
else
{
r->next=s;
r=s;
}
}
if(r!=NULL)
r->next=NULL;
r=Hc; //输出链表C
while(r!=NULL)
{
cout<<r->num<<" ";
r=r->next;
}
cout<<endl;
}