一、双指针,我fo了。。。。。
1 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 2 if (headA == nullptr || headB == nullptr) 3 return nullptr; 4 ListNode* tempa = headA; 5 ListNode* tempb = headB; 6 ListNode* res = nullptr; 7 int count1 = 0; 8 int count2 = 0; 9 10 while (count1 < 2 && count2 < 2) 11 { 12 if (count1 == 1 && count2 == 1 && tempa == tempb) 13 { 14 res = tempa; 15 break; 16 } 17 tempa = tempa->next; 18 if (tempa == nullptr) 19 { 20 tempa = headB; 21 count1++; 22 } 23 tempb = tempb->next; 24 if (tempb == nullptr) 25 { 26 tempb = headA; 27 count2++; 28 } 29 } 30 return res; 31 }
二、数长度法
代码不贴了
三、看不懂法
floyd判环算法还行。。我是一只酸菜鱼,又酸又菜又多余
1 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 2 if (headA == nullptr || headB == nullptr) 3 return nullptr; 4 ListNode* tempa = headA; 5 while (tempa->next != nullptr) 6 { 7 tempa = tempa->next; 8 } 9 tempa->next = headA; 10 11 ListNode* fast = headB; 12 ListNode* slow = headB; 13 while (fast != nullptr &&fast->next != nullptr) 14 { 15 fast = fast->next->next; 16 slow = slow->next; 17 if (fast == slow) 18 { 19 break; 20 } 21 } 22 if (fast == nullptr || fast->next==nullptr) 23 { 24 tempa->next = nullptr; 25 return nullptr; 26 } 27 28 slow = headB; 29 while (slow != fast) 30 { 31 slow = slow->next; 32 fast = fast->next; 33 } 34 tempa->next = nullptr; 35 return slow; 36 }