题解 | #两个链表的第一个公共结点#

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

http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

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

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.*;

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
     HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
       if(pHead1==null||pHead2==null) return null;
        int len1=0;
        ListNode tmp1=pHead1;
        ListNode tmp2=pHead2;
        while(tmp1.next!=null){
            tmp1=tmp1.next;
            len1++;
        }
        int len2=0;
        while(tmp2.next!=null){
            tmp2=tmp2.next;
            len2++;
        }
        if(len1>len2){
            for(int i=0;i<len1-len2;i++){
                pHead1=pHead1.next;
            }
        }
        if(len2>len1){
            for(int i=0;i<len2-len1;i++){
                pHead2=pHead2.next;
            }
        }
        while(pHead1!=null&&pHead2!=null&&pHead1.val!=pHead2.val){
            pHead1=pHead1.next;
            pHead2=pHead2.next;
        }
        return pHead1;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务