相交链表

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/在这里插入图片描述
编写一个程序,找到两个单链表相交的起始节点。

package factory;

import base.ListNode;

/**
 * @Auther: Jaryn
 * @Date: 2019/12/9 22:31
 * @Description: 相交链表
 * https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/265/linked-list/1148/
 * 算出A的长度,B的长度,A>B 则A先走a-b步,直到相遇
 */
public class GetIntersectionNode {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);

        ListNode listNode11 = new ListNode(11);
        ListNode listNode12 = new ListNode(12);
        ListNode listNode13 = new ListNode(13);
        ListNode listNode14 = new ListNode(14);
        ListNode listNode15 = new ListNode(15);
        ListNode listNode16 = new ListNode(16);


//        listNode1.setNext(listNode2);
        listNode2.setNext(listNode3);
        listNode3.setNext(null);
//        listNode4.setNext(listNode5);
//        listNode5.setNext(listNode13);
//
//        listNode11.setNext(listNode12);
//        listNode12.setNext(listNode13);
//        listNode13.setNext(listNode14);
//        listNode14.setNext(listNode15);
//        listNode15.setNext(listNode16);
        System.out.println(getIntersectionNode(listNode2, listNode3).getVal());
    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) {
            return null;
        }
        if(headA == headB) {
            return headA;
        }
        int alen = 1;
        int blen = 1;
        ListNode tempA = headA;

        int com = 0;
        while (tempA.getNext() != null) {
            tempA = tempA.getNext();
            alen +=1 ;
        }
        ListNode tempB = headB;
        while (tempB.getNext() != null) {
            tempB = tempB.getNext();
            blen +=1 ;
        }
        tempA = headA;
        tempB = headB;
        if(alen > blen) {
            com = alen - blen;
            while (com > 0) {
                tempA = tempA.getNext();
                com--;
            }
        }else {
            com = blen - alen;
            while (com > 0) {
                tempB = tempB.getNext();
                com--;
            }
        }
        while (tempA != null) {
            if(tempA == tempB) {
                return tempA;
            }
            tempA = tempA.getNext();
            tempB = tempB.getNext();
        }
        return null;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值