题目
给定两个单链表的头节点head1和head2,如何判断两个链表是否相交?相交的话返回true,不想交的话返回false。
给定两个链表的头结点head1和head2,请返回一个bool值代表它们是否相交。
思路
重点是要把有环和无环的情况都想到。
参考:【链表问题】判断有环单链表是否相交、【链表问题】判断无环单链表是否相交、【链表问题】单向链表判断是否有环、求入环节点、求环长、求链表长度
代码实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class ChkIntersection {
public:
ListNode* ifCircle(ListNode* head){//判断链表是否有环,若有环返回入环节点,否则返回null
if(head == NULL || head->next == NULL)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow)//有环
{
fast = head;
while(fast!=slow)
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
return NULL;
}
bool circleCross(ListNode* head1,ListNode* head2){//两个都有环,判断是否相交
ListNode* enter1 = ifCircle(head1);
ListNode* enter2 = ifCircle(head2);
if(enter1 == enter2)
return true;
else{
ListNode* temp = enter1->next;
while(temp != enter1){
if(temp==enter2)
return true;
temp = temp->next;
}
}
return false;
}
bool noCircleCross(ListNode* head1,ListNode*head2){//两个都无环,判断是否相交
while(head1->next!=NULL){
head1= head1->next;
}
while(head2->next!=NULL){
head2= head2->next;
}
if(head1 == head2)
return true;
else
return false;
}
bool chkInter(ListNode* head1, ListNode* head2) {
// write code here
if(head1 == NULL || head2 == NULL)
return false;
//判断是否有环
ListNode* enter1 = ifCircle(head1);
ListNode* enter2 = ifCircle(head2);
if(enter1 == NULL && enter2 == NULL){//都无环
if(noCircleCross(head1,head2))//相交
return true;
else
return false;
}
if(enter1 !=NULL && enter2 !=NULL){//都有环
if (circleCross(head1,head2))//有环相交
return true;
else
return false;
}
return false;//一个有环,一个无环的话一定不相交
}
};