題目:
https://leetcode.com/problems/intersection-of-two-linked-lists/
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
| class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA == nullptr || headB == nullptr) return nullptr; ListNode* a = headA; ListNode* b = headB;
int diff = 0; while(a != nullptr){ a = a->next; diff++; } while(b != nullptr){ b = b->next; diff--; }
if(a != b) return nullptr;
if(diff >= 0){ a = headA; b = headB; } else{ a = headB; b = headA; } diff = abs(diff); while(diff > 0){ a = a->next; diff--; } while(a != b){ a = a->next; b = b->next; } return a; } };
|