标签:
由于是单链表,需要保存链表头
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL)
{
return NULL;
}
int lengthA = 0, lengthB = 0;
ListNode* tmpA = headA;
ListNode* tmpB = headB;
while (tmpA->next != NULL)
{
lengthA++;
tmpA = tmpA->next;
}
while (tmpB->next != NULL)
{
lengthB++;
tmpB = tmpB->next;
}
if (tmpA->val != tmpB->val)
return NULL;
tmpA = headA;
tmpB = headB;
if (lengthA >lengthB)
{
for (size_t i = 0; i < lengthA-lengthB; i++)
{
headA = headA->next;
}
}
else
{
for (size_t i = 0; i < lengthB - lengthA; i++)
{
headB = headB->next;
}
}
while (headA != NULL)
{
if (headA->val == headB->val)
{
return headA;
}
else
{
headA = headA->next;
headB = headB->next;
}
}
}
};
Intersection of Two Linked Lists
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/4321391.html