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

\(\color{#00FF00}{题目描述}\)

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


import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
     List<ListNode> list = new ArrayList<ListNode>();
     if(pHead1==null||pHead2==null) return null;
     boolean flag=false;
     ListNode p2=pHead2;   
        while(pHead1!=null){
            pHead2=p2;
        while(pHead2!=null){
            if(pHead1.val==pHead2.val){
                list.add(pHead1);
                flag=true;
                break;
            }else{
                pHead2=pHead2.next;
            }
        }
            pHead1=pHead1.next;
     }
        if(flag) return list.get(0);
        return null;
    }
}

posted @ 2020-01-19 12:21  浅滩浅  阅读(98)  评论(0)    收藏  举报