两个链表的第一个公共结点

本文介绍两种高效算法来确定两个链表的第一个公共结点,包括利用链表长度差的方法和使用HashMap进行查找的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两个链表的第一个公共结点

两个链表第一个公共结点后都是公共结点,呈Y型,非X型。也就是说两个链表在第一个节点重合之后不会再分开了
这里写图片描述

方法一:利用两个链表的长度差

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode p1=pHead1;//链表1
        ListNode p2=pHead2;//链表2
        if(p1==null||p2==null)
            return null;
        int length1=getLength(p1);
        int length2=getLength(p2);

        //求得两链表的长度差,使其较长的链表当前结点遍历一个长度差
        if(length1>=length2){
              int len=length1-length2;
            while(len>0){
                p1=p1.next;
                len--;
            }
        }
        else {
            int len=length2-length1;
            while(len>0){
                p2=p2.next;
                len--;
            }
        }

        //开始齐头并进,直到找到第一个公共结点
        while(p1!=p2){
            p1=p1.next;
            p2=p2.next;
        }
        return p1;

    }
    //求链表长度
    public static int getLength(ListNode pHead){
        int length=0;
        ListNode current=pHead;
        while(current!=null){
            length++;
            current=current.next;
        }
        return length;
    }
}

方法二:利用HashMap中containsKey()函数,调用containsKey方法查询是否包含指定的键名。

import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode current1=pHead1;
        ListNode current2=pHead2;
        HashMap<ListNode,Integer> hashMap=new HashMap<ListNode,Integer>();
        while(current1!=null){
            hashMap.put(current1,null);
            current1=current1.next;
        }
        while(current2!=null){
            if(hashMap.containsKey(current2)){
                return current2;
            }
            current2=current2.next;
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值