描述

输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)

示例

输入:{1,2,3},{4,5},{6,7} 输出:{6,7} 说明:第一个参数{1,2,3}代表是第一个链表非公共部分,第二个参数{4,5}代表是第二个链表非公共部分,最后的{6,7}表示的是2个链表的公共部分 这3个参数最后在后台会组装成为2个两个无环的单链表,且是有公共节点的

思路

本题使用了两个for循环

代码

/*
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 node = null;
        if(pHead1 == null || pHead2 == null){
             return node;
         }else {
            while(pHead1.next != null && pHead2.next != null){
                if(pHead1.val == pHead2.val){
                    return pHead1;
                }else{
                    pHead1 = pHead1.next;
                    pHead2 = pHead2.next;
                }
            }
            return node;
        }*/
        for (ListNode h1 = pHead1; h1 != null ; h1 = h1.next) {
            for (ListNode h2 = pHead2; h2 != null ; h2 = h2.next) {
                if (h1 == h2) return h1;
            }
        }
        return null;
    }
}