不考虑单链表有环的情况下
如果2个单链表相交,一定是Y型链表
1.遍历2个链表到尾结点,记录2个链表的长度x,y
2.尾结点相同,则相交。
3.从表头开始,长链表先走|x-y|步,之后2个链表一起走,判断第一个相同的点。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 typedef struct student //定义链表结构 5 { 6 int num; 7 struct student *pnext; 8 }stu,*pstu; 9 void link_tail_insert(pstu ,pstu ,int ); //尾插法建立2个链表 10 void link_show(pstu ); //展示链表 11 void link_judge_intersect(pstu ,pstu ); //判断链表是否有交点 12 void link_bulid_intersect(pstu ,pstu ,pstu ,pstu *); //建立Y型链表 13 void main(){ 14 pstu phead1,ptail1,phead2,ptail2; 15 int i; 16 phead1 = NULL; 17 ptail1 = NULL; 18 phead2 = NULL; 19 ptail2 = NULL; 20 while(scanf("%d",&i) != EOF){ 21 link_tail_insert(&phead1,&ptail1,i); 22 link_tail_insert(&phead2,&ptail2,i); 23 } 24 link_show(phead1); 25 link_bulid_intersect(phead1,phead2,ptail1,&ptail2); 26 link_show(phead2); 27 link_judge_intersect(phead1,phead2); 28 system("pause"); 29 30 } 31 void link_tail_insert(pstu *phead,pstu *ptail,int i){ //尾插法建立链表 32 pstu pnew; 33 pnew = (pstu)malloc(sizeof(stu)); 34 memset(pnew,0,sizeof(stu)); 35 pnew->num = i; 36 if(*ptail == NULL){ 37 *phead = pnew; 38 *ptail = pnew; 39 } 40 else{ 41 (*ptail)->pnext = pnew; 42 *ptail = pnew; 43 } 44 } 45 void link_show(pstu phead){ //输出链表 46 pstu pshow; 47 pshow = phead; 48 if(phead == NULL) 49 { 50 printf("no exsit\n"); 51 return; 52 } 53 while(pshow != NULL){ 54 printf("%d ",pshow->num); 55 pshow = pshow->pnext; 56 } 57 putchar('\n'); 58 } 59 void link_bulid_intersect(pstu phead1,pstu phead2,pstu ptail1,pstu *ptail2){ //把第2个链表拼接到第一个链表第三个结点的位置。 60 pstu i; 61 i = phead1; 62 i = i->pnext->pnext; 63 (*ptail2)->pnext = i; 64 *ptail2 = ptail1; 65 } 66 void link_judge_intersect(pstu phead1,pstu phead2){ //判断链表是否有交点 67 int x,y; 68 pstu i,j,prei,prej; 69 x = y = 0; 70 i = prei = phead1; //建立前置结点,和当前结点 71 j = prej = phead2; 72 while(i != NULL){ //2个链表运行到尾部 73 prei = i; 74 i = i->pnext; 75 x++; 76 } 77 while(j != NULL){ 78 prej = j; 79 j = j->pnext; 80 y++; 81 } 82 if(prei != prej) //尾结点不相同 没有相交 83 printf("Link has no intersect.\n"); 84 else{ 85 i = phead1; 86 j = phead2; 87 if(x > y){ //第1个链表长度长,先走X-Y步 88 x = x - y; 89 while(x > 0){ 90 i = i->pnext; 91 x--; 92 } 93 while(i != NULL){ //一起走,知道相遇或者达到NULL 94 if(i == j){ 95 printf("Link has intersect.\n"); 96 printf("%d\n",i->num); 97 break; 98 } 99 i = i->pnext; 100 j = j->pnext; 101 } 102 } 103 else{ 104 y = y - x; //第2个链表长度长,先走X-Y步 105 while(y > 0){ 106 j = j->pnext; 107 y--; 108 } 109 while(i != NULL){ //一起走,知道相遇或者达到NULL 110 if(i == j){ 111 printf("Link has intersect.\n"); 112 printf("%d\n",i->num); 113 break; 114 } 115 i = i->pnext; 116 j = j->pnext; 117 } 118 } 119 120 } 121 }