剑指Offer36:两个链表的第一个公共结点(Java)

参考lizo的解答:https://www.nowcoder.com/questionTerminal/6ab1d9a29e88450685099d45c9e31e46?f=discussion

思路分析:

首先明确,若两个链表有共同的节点则说明两个链表有相同的结尾。
求两条链表的长度,得长度之差,长的链表遍历几个结点直到剩下的节点长度和短的链表一样长。然后两天链表同时遍历,若存在公共结点,则会有结点值相等,若不存在,则会一直遍历到空。
考察链表的理解运用。

题目描述:

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

Java代码:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
    int len1=nodelength(pHead1);
    int len2=nodelength(pHead2);
//    if(pHead1.next==null||pHead2.next==null||len1==0||len2==0){
//        return null;
//    }    这个题不用判断两个链表是否为空,我不懂,麻烦大神低下评论指导
    if(len1>len2){
        for(int i=0;i<len1-len2;i++){
            pHead1=pHead1.next;
        }
    }else if(len1<len2){
        for(int i=0;i<len2-len1;i++){
            pHead2=pHead2.next;
        }
    }
        while(pHead1!=null){
            if(pHead1.val==pHead2.val){
                return pHead1;
            }
            pHead1=pHead1.next;
            pHead2=pHead2.next;
        }
        return null;
    }
   
    public static int nodelength(ListNode pHead){
        if (pHead==null) 
            return 0;
        int length=0;
        while(pHead!=null){
            pHead=pHead.next;
            length++;
        }
        return length;
    }
}
原文地址:https://www.cnblogs.com/dongmm031/p/12222303.html