【试题描述】
记
N = length(h1)
M = length(h2)
方法一:暴力搜索,时间复杂度为O(N*M)
方法二:时间复杂度为O(N+M)
方法三:
方法四:时间复杂度为O(N+M)
方法五:
typedef struct Node
{
int data;
struct Node *next;
}Node;
Node* FindIntersection(Node *pHead1, Node *pHead2)
{
if(NULL == pHead1 || NULL == pHead2)
{
return NULL;
}
Node *pCurrent1, *pCurrent2;
pCurrent1 = pHead1;
pCurrent2 = pHead2;
int len1 = 0, int len2 =0;
int diff = 0;
while(NULL != pCurrent1)
{
pCurrent1 = pCurrent1 -> next;
len1++;
}
while(NULL != pCurrent2)
{
pCurrent2 = pCurrent2 -> next;
len2++;
}
if(pCurrent1 != pCurrent2)
return NULL;
diff = abs(len1 - len2);
if(len1 > len2)
{
pCurrent1 = pHead1;
pCurrent2 = pHead2;
}
else
{
pCurrent1 = pHead2;
pCurrent2 = pHead1;
}
for(int i=0; i<diff; i++)
pCurrent1 = pCurrent1->next;
while(pCurrent1 != pCurrent2)
{
pCurrent1 = pCurrent1->next;
pCurrent2 = pCurrent2->next;
}
return pCurrent1;
}