看了大家的题解,发现重点就是解决链表长度不一致的问题
用了笨方法,先把链表长度的差值x计算出来,让长链表先走x步,然后同步向下走就得到了第一个公共节点。(其实可以利用两个链表长度和是一致解决)
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if(pHead1==pHead2)return pHead1; ListNode t1 = pHead1; ListNode t2 = pHead2; while(t1!=null&&t2!=null){ t1 = t1.next; t2 = t2.next; } int count = 0; if(t1!=null){ while(t1!=null){ t1 = t1.next; count++; } for (int i = 0; i <count ; i++) { pHead1=pHead1.next; } while(pHead1!=null&pHead2!=null){ if(pHead1==pHead2) return pHead1; pHead1=pHead1.next; pHead2 = pHead2.next; } } if(t2!=null){ while(t2!=null){ t2=t2.next; count++; } for (int i = 0; i <count ; i++) { pHead2=pHead2.next; } while(pHead1!=null&pHead2!=null){ if(pHead1==pHead2) return pHead1; pHead1=pHead1.next; pHead2 = pHead2.next; } } return null; }