您的位置:首页 > 其它

flag4给出俩个单向链表的头指针,比如pA,pB,判断这俩个链表是否相交

2018-01-22 22:21 417 查看
//给出俩个单向链表的头指针,比如pA,pB,判断这俩个链表是否相交

# include <stdio.h>

# include <malloc.h>

# include <math.h>

typedef struct node

{
int data;
struct node* next;

}Node,*Pnode;

Pnode creatnode();

void travel(Pnode L);

int leng(Pnode L);

bool compare(Pnode pA,Pnode pB);

void main()

{

Pnode pA,pB;

pA=creatnode();//创建pA

pB=creatnode();//创建pB

//travel(pA);

//travel(pB);

printf("number=%d\n",leng(pA));

if(compare(pA,pB))//如果相同输出OK 否则输出fail

printf("OK");

else
printf("fail");

}

Pnode creatnode()

{
int a,i;
Pnode L=(Pnode)malloc(sizeof(Node));
L->next=NULL;
printf("input your number\n");
scanf("%d",&a);
Pnode ptail=L;
for(i=0;i<a;i++)
{
Pnode pnew=(Pnode)malloc(sizeof(Node));
scanf("%d",&(pnew->data));
pnew->next=NULL;
ptail->next=pnew;
ptail=pnew;
}
return L;

}

void travel(Pnode L)

{
Pnode phead=L->next;
while(NULL!=phead)
{
printf("%d\n",phead->data);
phead=phead->next;
}

}

int leng(Pnode L)

{
int i=0;
Pnode phead=L->next;
while(L!=NULL)
{
i++;
L=L->next;
}
return i;

}

bool compare(Pnode pA,Pnode pB)

{
int i;
int a=leng(pA)-leng(pB);
Pnode Ahead=pA->next;
Pnode Bhead=pB->next;
for(i=0;i<a;i++)//核心 谁长谁先走,这里为了方便假设pA长
{
Ahead=Ahead->next;
}
while(Ahead!=NULL && Bhead!=NULL)
{
if(Ahead->data != Bhead->data)
break;//如果不同 立刻跳出循环体
else
{
Ahead=Ahead->next;
Bhead=Bhead->next;
}
}
if(Ahead==NULL && Bhead==NULL )
return true;
else 
return false;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐