判断两个链表是否相交

解题思路:首先分别判断两个链表是否存在环。

                   (1)如果两个链表都不存在环,则直接比较两个链表的表尾节点是否相等即可,如果相等,则相交,否则不想交。

                   (2)如果一个链表存在环,而另一个链表不存在环,则两个链表肯定不相交。

                   (3)如果两个链表都存在环。则如果两个链表相交的话则一个链表肯定共用环。通过判断一个链表中任意一个环内节点是否在另一个链表中即可判断两个链表是否相交

 

include "stdafx.h"

  
struct Node
{
     int value;
     Node * next;
};
  
//判断是否有环,返回bool,如果有环,返回环里的节点
bool isCircle(Node * head, Node *& circleNode, Node *& lastNode)
{
     Node * fast = head->next;
     Node * slow = head;
     while (fast != slow && fast && slow)
     {
         if (fast->next != NULL)
             fast = fast->next;
  
         if (fast->next == NULL)
             lastNode = fast;
         if (slow->next == NULL)
             lastNode = slow;
  
         fast = fast->next;
         slow = slow->next;
          
     }
     if (fast == slow && fast && slow)
     {
         circleNode = fast;
         return true ;
     }
     else
         return false ;
}
  
  
bool detect(Node * head1, Node * head2)
{
     Node * circleNode1;
     Node * circleNode2;
     Node * lastNode1;
     Node * lastNode2;
  
     bool isCircle1 = isCircle(head1,circleNode1, lastNode1);
     bool isCircle2 = isCircle(head2,circleNode2, lastNode2);
  
     //一个有环,一个无环
     if (isCircle1 != isCircle2)
         return false ;
     //两个都无环,判断最后一个节点是否相等
     else if (!isCircle1 && !isCircle2)
     {
         return lastNode1 == lastNode2;
     }
     //两个都有环,判断环里的节点是否能到达另一个链表环里的节点
     else
     {
         Node * temp = circleNode1;
         while (temp != circleNode1)
         {
             if (temp == circleNode2)
                 return true ;
             temp = temp->next;
         }
         return false ;
     }
  
     return false ;
}
  
int _tmain( int argc, _TCHAR* argv[])
{
     Node * n1 = new Node();
     Node * n2 = new Node();
     Node * n3 = new Node();
     Node * n4 = new Node();
  
     n1->next = n2;
     n2->next = n3;
     n3->next = n4;
     n4->next = NULL;
  
  
     Node * n5 = new Node();
     Node * n6 = new Node();
     Node * n7 = new Node();
     Node * n8 = new Node();
  
     n5->next = n6;
     n6->next = n7;
     n7->next = n8;
     n8->next = n5;
  
     if (detect(n1,n2))
         printf( "相交\n" );
     else
         printf( "不相交\n" );
  
     return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值