/**
* 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==NULL||headB==NULL) return NULL;
ListNode *tempA=headA,*tempB=headB;
int lenA=0,lenB=0,dlen;
while(tempA!=NULL) {lenA++;tempA=tempA->next;}
while(tempB!=NULL) {lenB++;tempB=tempB->next;}
dlen=lenA-lenB>0?lenA-lenB:lenB-lenA;
if(lenA>=lenB){
tempA=headA;tempB=headB;
}
else {tempA=headB;tempB=headA;}
while(dlen>0) {tempA=tempA->next;dlen--;}
while(tempA!=NULL)
{
if(tempA==tempB) return tempA;
else{tempA=tempA->next;tempB=tempB->next;}
}
return NULL;
}
};
Intersection of Two Linked Lists
最新推荐文章于 2020-12-24 13:01:16 发布