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

版权声明:本博客可任意转载,不用通知 https://blog.csdn.net/hbkzhu13579/article/details/84490607

链接

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

题目描述

输入两个链表,找出它们的第一个公共结点。

思路

俩个链表存在公共结点,意味着第一个公共结点之后的都是相同的,就是说,两个链表的尾巴是相同的,我们可以分别算出两个链表的长度之差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;
	}
}

猜你喜欢

转载自blog.csdn.net/hbkzhu13579/article/details/84490607