//方案一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