java相关-链表-链表相交-力扣0207

package com.company;

public class Solution {
    public static void main(String[] args) {
        ListNode headA = new ListNode(4);
        ListNode node2 = new ListNode(1);
        headA.next = node2;
        ListNode node3 = new ListNode(8);
        node2.next = node3;
        ListNode node4 = new ListNode(4);
        node3.next = node4;
        ListNode node5 = new ListNode(5);
        node4.next = node5;


        ListNode headB = new ListNode(5);
        ListNode n2 = new ListNode(0);
        headB.next = n2;
        ListNode n3 = new ListNode(1);
        n2.next = n3;

        n3.next = node3;

        ListNode t = getIntersectionNode(headA, headB);

    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        if (headA == null || headB == null) {
            return null;
        }

        int lenA = 0;
        ListNode tmpA = headA;
        ListNode tmpB = headB;
        while (tmpA != null) {//获取长度
            lenA++;
            tmpA = tmpA.next;

        }

        int lenB = 0;
        while (tmpB != null) {//获取长度
            lenB++;
            tmpB = tmpB.next;

        }


        ListNode curB = headB;
        ListNode curA = headA;
        if (lenB > lenA) {//谁的长度长,往后移动节点到相同长度的位置(从后往前数节点数相同)
            for (int i = 0; i < lenB - lenA; i++) {
                curB = curB.next;
            }

        } else {//谁的长度长,往后移动节点到相同长度的位置(从后往前数节点数相同)
            for (int i = 0; i < lenA - lenB; i++) {
                curA = curA.next;
            }
        }
        while (curA != null) {//长度相同后,再同时向后移动,获取相同指针的节点
            if (curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值