问题:
微软亚院之编程判断俩个链表是否相交
给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。
为了简化问题,我们假设俩个链表均不带环。
答案:
//20121125
#include <iostream>
using namespace std;
typedef struct node
{
int num;
node* next;
}node;
void generateList(const bool cross,node *&head1,node *&head2);
//true代表产生的链表相交,false代表不相交
bool crossORnot(node *head1,node *head2);
int main()
{
node* head1=NULL;
node* head2=NULL;
generateList(false,head1,head2);
if (crossORnot(head1,head2))
{
cout<<"cross true"<<endl;
}
else
{
cout<<"cross false"<<endl;
}
return 0;
}
//假设链表不带环
void generateList(const bool cross,node *&head1,node *&head2)
{
//每个链表都具有10个节点
node *pre1=NULL;
node *p=new node;
head1=p;
p->num=rand();
p->next=NULL;
pre1=p;
node *pre2=NULL;
p=new node;
head2=p;
p->num=rand();
p->next=NULL;
pre2=p;
if (cross)
{
//假设从第3个节点开始相交
int crossID=3;
for (int i=0;i<10;++i)
{
//第一条链表的节点
p=new node;
pre1->next=p;
p->num=rand();
p->next=NULL;
pre1=p;
if (i<crossID)
{
//第二条链表的节点
p=new node;
pre2->next=p;
p->num=rand();
p->next=NULL;
pre2=p;
}
else
{
if (i==crossID)
{
pre2->next=p;
}
}
}
}
else
{
for (int i=0;i<10;++i)
{
//第一条链表的节点
p=new node;
pre1->next=p;
p->num=rand();
p->next=NULL;
pre1=p;
//第二条链表的节点
p=new node;
pre2->next=p;
p->num=rand();
p->next=NULL;
pre2=p;
}
}
}
bool crossORnot(node *head1,node *head2)
{
while (head1->next!=NULL)
{
head1=head1->next;
}
while (head2->next!=NULL)
{
head2=head2->next;
}
if (head1==head2)
{
return true;
}
else
{
return false;
}
}