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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
class Solution { public: int get_length(const ListNode* pHead) { int len = 0; while (pHead != nullptr) { pHead = pHead->next; len++; } return len; } ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { int a = get_length(pHead1); int b = get_length(pHead2); if (a < b) { int d = b - a; for (int i = 0; i < d; i++) { pHead2 = pHead2->next; } } else { int d = a - b; for (int i = 0; i < d; i++) { pHead1 = pHead1->next; } } while (pHead1 != pHead2) { if (pHead1 == nullptr || pHead2 == nullptr) { return nullptr; } else { pHead1 = pHead1->next; pHead2 = pHead2->next; } } return pHead1; } };
|