1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int firstLen = getListLength(pHead1); int secondLen = getListLength(pHead2); int diff = firstLen - secondLen;
if (diff > 0) pHead1 = findFirstNodeHelper(pHead1, diff); else if (diff < 0) pHead2 = findFirstNodeHelper(pHead2, -diff);
while (pHead1 != null && pHead2 != null && pHead1 != pHead2) { pHead1 = pHead1.next; pHead2 = pHead2.next; }
return pHead1; }
private int getListLength(ListNode head) { int count = 0;
while (head != null) { count++; head = head.next; }
return count; }
private ListNode findFirstNodeHelper(ListNode head, int step) { while (step != 0) { step--; head = head.next; }
return head; }
|
近期评论