不考虑单链表有环的情况下
如果2个单链表相交,一定是Y型链表
1.遍历2个链表到尾结点,记录2个链表的长度x,y
2.尾结点相同,则相交。
3.从表头开始,长链表先走|x-y|步,之后2个链表一起走,判断第一个相同的点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student //定义链表结构
{
int num;
struct student *pnext;
}stu,*pstu;
void link_tail_insert(pstu ,pstu ,int ); //尾插法建立2个链表
void link_show(pstu ); //展示链表
void link_judge_intersect(pstu ,pstu ); //判断链表是否有交点
void link_bulid_intersect(pstu ,pstu ,pstu ,pstu *); //建立Y型链表
void main(){
pstu phead1,ptail1,phead2,ptail2;
int i;
phead1 = NULL;
ptail1 = NULL;
phead2 = NULL;
ptail2 = NULL;
while(scanf("%d",&i) != EOF){
link_tail_insert(&phead1,&ptail1,i);
link_tail_insert(&phead2,&ptail2,i);
}
link_show(phead1);
link_bulid_intersect(phead1,phead2,ptail1,&ptail2);
link_show(phead2);
link_judge_intersect(phead1,phead2);
system("pause");
}
void link_tail_insert(pstu *phead,pstu *ptail,int i){ //尾插法建立链表
pstu pnew;
pnew = (pstu)malloc(sizeof(stu));
memset(pnew,0,sizeof(stu));
pnew->num = i;
if(*ptail == NULL){
*phead = pnew;
*ptail = pnew;
}
else{
(*ptail)->pnext = pnew;
*ptail = pnew;
}
}
void link_show(pstu phead){ //输出链表
pstu pshow;
pshow = phead;
if(phead == NULL)
{
printf("no exsit\n");
return;
}
while(pshow != NULL){
printf("%d ",pshow->num);
pshow = pshow->pnext;
}
putchar('\n');
}
void link_bulid_intersect(pstu phead1,pstu phead2,pstu ptail1,pstu *ptail2){ //把第2个链表拼接到第一个链表第三个结点的位置。
pstu i;
i = phead1;
i = i->pnext->pnext;
(*ptail2)->pnext = i;
*ptail2 = ptail1;
}
void link_judge_intersect(pstu phead1,pstu phead2){ //判断链表是否有交点
int x,y;
pstu i,j,prei,prej;
x = y = 0;
i = prei = phead1; //建立前置结点,和当前结点
j = prej = phead2;
while(i != NULL){ //2个链表运行到尾部
prei = i;
i = i->pnext;
x++;
}
while(j != NULL){
prej = j;
j = j->pnext;
y++;
}
if(prei != prej) //尾结点不相同 没有相交
printf("Link has no intersect.\n");
else{
i = phead1;
j = phead2;
if(x > y){ //第1个链表长度长,先走X-Y步
x = x - y;
while(x > 0){
i = i->pnext;
x--;
}
while(i != NULL){ //一起走,知道相遇或者达到NULL
if(i == j){
printf("Link has intersect.\n");
printf("%d\n",i->num);
break;
}
i = i->pnext;
j = j->pnext;
}
}
else{
y = y - x; //第2个链表长度长,先走X-Y步
while(y > 0){
j = j->pnext;
y--;
}
while(i != NULL){ //一起走,知道相遇或者达到NULL
if(i == j){
printf("Link has intersect.\n");
printf("%d\n",i->num);
break;
}
i = i->pnext;
j = j->pnext;
}
}
}
}