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

//方案一code

public class Solution {io

public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {

   ListNode temp1=pHead1;
   ListNode temp2=pHead2;
    
    if(pHead1==null||pHead2==null)
        return null;
   
    
   while(temp1!=null||temp2!=null){
       if(temp1==null)
           temp1=pHead1;
       if(temp2==null)
           temp2=pHead2;
       
       if(temp1==temp2)
           return temp1;
       
       temp1=temp1.next;
       temp2=temp2.next;
   } 
   
   //这个地方返回空的缘由:是说没有公共节点,都最后一个节点都是空
   
 return null;
}

}class

//方案二:List

public class Solution {循环

public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {

   ListNode temp1=pHead1;
   ListNode temp2=pHead2;
    
    while(temp1!=temp2)
    {
        temp1=temp1==null?pHead2:temp1.next;
        temp2=temp2==null?pHead1:temp2.next;
    }
    
    return temp1;
}

}next

方案二更好,循环的次数更少while

相关文章
相关标签/搜索