《剑指offer》系列 两个链表的第一个公共结点(Java)

链接

牛客:两个链表的第一个公共结点

LeetCode:剑指 Offer 52. 两个链表的第一个公共节点

160. 相交链表

思路

两个链表存在公共结点,意味着第一个公共结点之后的都是相同的,就是说,两个链表的尾巴是相同的,我们可以分别算出两个链表的长度之差lenDif ,然后遍历长链表到lenDif的位置,再一起遍历两个链表,找到第一个相同的即可。

代码

牛客:

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
		int len1 = getLen(pHead1);
		int len2 = getLen(pHead2);
		int lenDif = 0;
		ListNode pLong = null;
		ListNode pShort = null;
		
		if(len1 >= len2){
			lenDif = len1-len2;
			pLong = pHead1;
			pShort = pHead2;
		} else {
			lenDif = len2-len1;
			pLong = pHead2;
			pShort = pHead1;
		}
		
		for(int i = 0; i < lenDif; i++){
			pLong = pLong.next;
		}
		
		while(pLong != null && pShort != null && pLong != pShort){
			pLong = pLong.next;
			pShort = pShort.next;
		}
		
		ListNode pFirstCommon = pLong;
		return pFirstCommon;
    }
    
    public int getLen(ListNode pHead){
		int len = 0;
		ListNode pNode = pHead;
		while(pNode!=null){
			len++;
			pNode = pNode.next;
		}
		return len;
	}
}

LeetCode:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值