您的位置:首页 > 编程语言

7.编程判断俩个链表是否相交

2014-12-16 11:00 302 查看
题目:给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。
为了简化问题,我们假设俩个链表均不带环。
问题扩展:
1.如果链表可能有环列?

2.如果需要求出俩个链表相交的第一个节点列?

第5题的加强版,具体分析可以看第5题.

代码实现:

typedef struct node{
int value;
struct node *next;
}Node;

Node *testCircle(Node *head)//判断链表是否存在环,如果存在环,则返回环的其中一个点
{
Node *slow,*fast;
if(head==NULL)
return NULL;
slow=head;
fast=head;
while(slow!=NULL&&fast!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)//找到环的其中一个点
return slow;
}
return NULL;
}

int isJoinedSimple(Node *head1,Node *head2)//判断两个无环链表是否相交
{
if(head1==NULL||head2==NULL)
return 0;
while(head1->next!=NULL)
head1=head1->next;
while(head2->next!=NULL)
head2=head2->next;
return head1==head2;
}

int isJoined(Node *head1,Node *head2)//判断两个链表是否相交
{
Node *circle1,*circle2;
circle1=testCircle(head1);
circle2=testCircle(head2);
if(circle1==NULL&&circle2==NULL)//两个链表都没形成环
return isJoinedSimple(head1,head2);
if(circle1!=NULL&&circle2!=NULL)//两个链表都形成环
{
if(circle1==circle2)
return 1;
Node *p=circle1;
p=circle1->next;
while(p!=circle1)//检查链表circle2节点是否在第一个链表的环里面
{
if(p==circle2)
return 1;
p=p->next;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: