【Leecode】 Instersection od Two Linked Lists
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(!headA || !headB) return nullptr;
int aLen = 0,bLen = 0;
int dis = 0;
ListNode* pA = headA;
ListNode* pB = headB;
while(pA){
pA = pA->next;
aLen++;
}
while(pB){
pB = pB->next;
bLen++;
}
pA = headA;;
pB = headB;
if(aLen >= bLen){
dis = aLen - bLen;
while(dis--){
pA = pA->next;
}
}
if(aLen < bLen){
dis = bLen - aLen;
while(dis--){
pB = pB->next;
}
}
while(pA && pB){
if(pA == pB) return pA;
pA = pA->next;
pB = pB->next;
}
return nullptr;
}
};
哈哈,终于刷到第50道了!!
浙公网安备 33010602011771号