给定两个单链表的头节点head1和head2,如何判断两个链表是否相交?相交的话返回true,不想交的话返回false。
给定两个链表的头结点head1和head2(注意,另外两个参数adjust0和adjust1用于调整数据,与本题求解无关)。请返回一个bool值代表它们是否相交。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class ChkIntersection {
public:
ListNode* chkLoop(ListNode* head) //判断链表是否有环,若有环,返回刚开始进环的结点
{
if(head==NULL||head->next==NULL)
return NULL;
ListNode *fast,*slow;
fast=slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
break;
}
if(fast==slow)
{
fast=head;
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
else
{
return NULL;
}
}
bool chkInter(ListNode* head1, ListNode* head2, int adjust0, int adjust1) {
// write code here
ListNode *start1,*start2;
start1=chkLoop(head1);
start2=chkLoop(head2);
if(start1==NULL&&start2==NULL)//无环单链表相交判断
{
ListNode* temp;
temp=head1;
int lena=0,lenb=0;
while(temp)
{
temp=temp->next;
lena++;
}
temp=head2;
while(temp)
{
temp=temp->next;
lenb++;
}
if(lena>lenb)
{
for(int i=0;i<lena-lenb;i++)
{
head1=head1->next;
}
while(head1)
{
if(head1==head2)
return true;
head1=head1->next;
head2=head2->next;
}
return false;
}
else
{
for(int i=0;i<lenb-lena;i++)
{
head2=head2->next;
}
while(head1)
{
if(head1==head2)
return true;
head1=head1->next;
head2=head2->next;
}
return false;
}
}
else if(start1!=NULL&&start2!=NULL)//有环单链表相交判断
{
if(start1==start2)
return true;
ListNode *p;
p=start1;
while(true)
{
p=p->next;
if(p==start1)
return false;
if(p==start2)
return true;
}
}
else{
return false;
}
}
};