题目:找2个链表的公共节点。
思路:遍历2遍,然后判断。
/**
* 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;
int len1=0,len2=0;
ListNode *a=headA;
ListNode *b=headB;
while(a!=NULL)
{
len1++;a=a->next;
}
while(b!=NULL)
{
len2++; b=b->next;
}
a=headA;
b=headB;
if(len1>=len2)
{
len1-=len2;
while(len1)
{
a=a->next; len1--;
}
}
else
{
len2-=len1;
while(len2)
{
b=b->next; len2--;
}
}
while(a!=NULL&&b!=NULL)
{
if(a==b) return a;
a=a->next;
b=b->next;
}
return NULL;
}
};