【链表问题】判断单向链表是否相交

题目

给定两个单链表的头节点head1和head2,如何判断两个链表是否相交?相交的话返回true,不想交的话返回false。

给定两个链表的头结点head1head2,请返回一个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;//一个有环,一个无环的话一定不相交
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值