判断两链表是否相交,返回交点(考虑带环)
linklist *linklist_iscrossplus(linklist *head1,linklist *head2)
{
if(head1 == NULL)
{
return NULL;
}
if(head2 == NULL)
{
return NULL;
}
else
{
linklist *cur1 = linklist_getenter(head1);
linklist *cur2 = linklist_getenter(head2);
if(cur1 == NULL && cur2 == NULL)
{
linklist_iscross(head1,head2);
}
else if((cur1 != NULL && cur2 == NULL) || (cur2 != NULL && cur1 == NULL))
{
return NULL;//这种情况不存在
}
else
{
if(cur1 == cur2)
{
//有交点,且交点在环外
linklist *pos1 = head1;
linklist *pos2 = head2;
int len1 = 0;
int len2 = 0;
while(pos1 != cur1)
{
pos1 = pos1->next;
len1++;
}
while(po2 != cur1)
{
pos2 = pos2->next;
len2++;
}
pos1 = head1;
pos2 = head2;
int len = 0;
if(len1-len2)
{
len = len1-len2;
while(len)
{
pos1 = pos1->next;
len--;
}
}
else
{
len = len2-len1;
while(len)
{
pos2 = pos2->next;
len--;
}
}
while(pos1 != pos2)
{
pos1 = pos1->next;
pos2 = pos2->next;
}
return pos1;
}
else
{
linklist *p1 = linklist_getenter(head1);
linklist *p2 = linklist_getenter(head2);
while(p1 != p2)
{
if(p1->next = p1)
{
return NULL;
}
p1 = p1->next;
}
return p1;
}
}
}
}
求两个有序链表的交集
linklist *linklist_union(linklist *head1,linklist *head2)
{
if(head1 == NULL)
{
return NULL;
}
if(head2 == NULL)
{
return NULL;
}
else
{
linklist *cur1 = head1;
linklist *cur2 = head2;
linklist *newhead = NULL;
linklist *newtail = NULL;
for(;cur1 !=NULL;cur1 = cur1->next)
{
for(cur2 = head2;cur2 != NULL;cur2 = cur2->next)
{
if(cur2->data = cur1->data)
{
if(newhead == newtail == NULL)
{
newtail = newhead = cur2;
}
else
{
newtail->next = cur2;
newtail = newtail->next;
}
}
}
}
return newhead;
}
}