160. 相交链表
题目链接:160. 相交链表
代码如下:
/**
* 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 lenA=getLength(headA);
int lenB=getLength(headB);
if(lenA==0||lenB==0) {return NULL;}
ListNode *pLonger,*pShorter;
if(lenA>lenB)
{
pLonger=headA;
pShorter=headB;
}
else
{
pLonger=headB;
pShorter=headA;
}
for(int i=0;i<abs(lenA-lenB);i++)
{
pLonger=pLonger->next;
}
while(pLonger&&pShorter)
{
if(pLonger==pShorter) {return pLonger;}
pLonger=pLonger->next;
pShorter=pShorter->next;
}
return NULL;
}
int getLength(ListNode *head)
{
int len=0;
ListNode* pHead=head;
while(pHead)
{
len++;
pHead=pHead->next;
}
return len;
}
};