判断2个链表是否相交,如果相交,求出交点

如果2个链表相交,一定有相同的尾结点

思路:分别遍历找到尾结点,比较,若相同则相交,否则不相交。如果相交,求出交点

public class XiangJiao {
    public static void main(String[] args){
        Node p1=new Node(5);
        Node p2=new Node(3);
        Node p3=new Node(9);
        Node p4=new Node(2);
        p1.next=p2;
        p2.next=p3;
        p3.next=p4;
        Node q1=new Node(6);
        Node q2=new Node(4);
        Node q3=new Node(7);
        Node q4=new Node(8);
        Node q5=new Node(2);
        q1.next=q2;
        q2.next=q3;
        q3.next=q4;
        q4.next=q5;
        System.out.println(new XiangJiao().isIntersect(p1,q1));
        Node n=getMeetNode(p1,q1);
        System.out.println(n.data);
    }
    public boolean isIntersect(Node h1,Node h2){
        if(h1==null||h2==null)
            return false;
        Node t1=h1;
        //找链表1的尾结点
        while(t1.next!=null)
            t1=t1.next;

        Node t2=h2;

        //找链表2的尾结点
        while(t2.next!=null)
            t2=t2.next;

        return t1.data==t2.data;


    }
    //判断是否相交,如果相交找出交点

    public  static Node getMeetNode(Node h1,Node h2){
        if(h1==null||h2==null)
            return null;
        Node t1=h1;
        int len1=1;
        //找链表1的尾结点
        while(t1.next!=null) {
            t1 = t1.next;
            len1++;
        }
        Node t2=h2;
        int len2=1;
        //找链表2的尾结点
        while(t2.next!=null) {
            t2 = t2.next;
            len2++;
        }
        //如果不相交
        if(t1.data!=t2.data){
            return null;
        }
        Node t_1=h1;
        Node t_2=h2;
        //找出较长的,先遍历
        if(len1>len2){
            int d=len1-len2;
            while (d!=0){
                t_1=t_1.next;
                d--;
            }
        }else{
            int d=len2-len1;
            while (d!=0){
                t_2=t_2.next;
                d--;
            }
        }
        while(t_1.data!=t_2.data){//同时遍历
            t_1=t_1.next;
            t_2=t_2.next;
        }
        return t_1;


    }

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值