Problem: 面试题 02.07. 链表相交
思路
相交节点后的链表是相同的,我们得到两个链表的长度差,开始同时从长度差后的节点同时遍历
错误
if(aLen < bLen)
这里一开始写反了
复杂度
$O(n+m)$
$O(1)$
Code
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
| class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *a = headA,*b = headB; while(a!=nullptr&&b!=nullptr){ a = a->next; b = b->next; } int diff = 0; ListNode *longList,*shortList; if(a==nullptr) { longList = headB; shortList = headA; }else { swap(a,b); longList = headA; shortList = headB; } while(b!=nullptr) { b = b->next; diff++; } while(diff--) longList = longList->next; while(longList != nullptr && shortList != nullptr && longList != shortList) { longList = longList->next; shortList = shortList->next; } return longList; } };
|
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
| class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* a = headA; ListNode* b = headB;
int aLen = 0; int bLen = 0;
while(a != nullptr) { aLen++; a = a->next; }
while(b != nullptr) { bLen++; b = b->next; }
a = headA; b = headB;
if(aLen < bLen) { swap(aLen,bLen); swap(a,b); }
int def = aLen - bLen; while(def--) { a = a->next; }
while(a != nullptr && a != b) { a = a->next; b = b->next; }
return a; } };
|