输入两个链表,找出它们的第一个公共结点。
//方案一
public class Solution {
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;
}
}
//方案二:
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;
}
}
方案二更好,循环的次数更少