编辑代码

#include <stdio.h>
#include <stdlib.h>
//定义一个单链表
typedef struct Link{
    int elem;
    struct Link * next;
}link;
//自定义的bool类型
typedef enum bool{
    False = 0,
    True = 1
}bool;
//L1和L2为2个单链表,函数返回True表示链表相交,返回False表示不相交
bool LinkIntersect(link * L1, link * L2){
    link * p1 = L1;
    link * p2 = L2;
    //逐个遍历L1链表中的各个节点
    while(p1){
        while(p2){
            if(p1 == p2){
                return True;
            }
            p2 = p2 ->next;
        }
        p1 = p1 ->next;
    }
    return False;
}
//最后一个节点只要相等,就是相交
bool LinkIntersect1(link *L1, link *L2){
    link * p1 = L1;
    link * p2 = L2;
    //找到链表1的最后一个节点
    while(p1->next){
        p1 = p1 ->next;
    }
    //找到链表2的最后一个节点
    while(p2->next){
        p2 = p2 ->next;
    }
    //判断L1和L2链表最后一个节点是否相同
    if(p1 == p2){
        return True;
    }
    return False;
}
//如果两个链表相交,则它们相交部分所包含的节点个数一定相等
bool LinkIntersect2(link * L1, link * L2){
    link * plong = L1;
    link * pshort = L2;
    link * temp = NULL;
    int num1 = 0, num2 = 0, step = 0;

    //得到L1的长度
    while(plong){
        num1++;
        plong = plong -> next;
    }
    //得到L2的长度
    while(pshort){
        num2++;
        pshort = pshort ->next;
    }
    //重置plong和pshort,使plong代表较长的链表,pshort代表较短的链表
    plong = L1;
    pshort = L2;
    step = num1 - num2;
    if(num1 < num2){
        plong = L2;
        pshort = L1;
        step = num2 = num1;
    }
    //在plong链表中找到和pshort等长度的子链表
    temp = plong;
    while (step){
        temp = temp -> next;
        step--;
    }
    //逐个比较temp和pshort链表中的节点是否相同
    while(temp && pshort){
        if(temp == pshort){
            return True;
        }
        temp = temp ->next;
        pshort = pshort ->next;
    }
    return False;
}
int main () {
    
    return 0;
}