/**
* 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) {
int sizea=0;
int sizeb=0;
ListNode *p=headA;
ListNode *q=headB;
if(!p||!q)return NULL;
while(p){
sizea++;
p=p->next;
}
while(q){
sizeb++;
q=q->next;
}
p=headA;
q=headB;
if(sizea>sizeb){
int cnt=sizea-sizeb;
while(cnt--){
p=p->next;
}
}else if(sizea<sizeb){
int cnt=sizeb-sizea;
while(cnt--){
q=q->next;
}
}
int flag=0;
while(q!=NULL&&p!=NULL){
if(p==q){
flag=1;
break;
}
p=p->next;
q=q->next;
}
if(flag==1){
return p;
}else return NULL;
}
};
面试题 02.07. 链表相交
最新推荐文章于 2024-09-13 19:36:07 发布