算法100题(第7题)

微笑题目:

判断两个单链表是否相交

给出两个单链表的头指针,比如h1,h2,判断这两个链表是否相交。

为了简化问题,假设两个链表均不带环

问题扩展:

1.如果链表可能有环列。

2.如果需要求出两个链表相交的第一个节点列?

struct Node{
int data;
    Node* next;
};
//if there is no cycle
int isJoinedSimple(Node* h1,Node* h2)
{
while (h1->next!=NULL)
          h1=h1->next;
while (h2->next!=NULL)
 h2=h2->next;
return h1==h2;
}

//if there could exists cycle
int  isJoined(Node* h1,Node* h2)
{
  Node* cylic1=textCylic(h1);
  Node* cylic2=textCylic(h2);
  if (cylic1+cylic2==0) return isJoinedSimple(h1,h2);
   if (cylic1==0&&cylic2!=0||cylic1!=0&&cylic2==0)
                         return 0;
  Node* p=cylic1;
  while (1)
  {
 if (p==cylic2||p->next==cylic2)
               return 1;
 p=p->next->next;
 cylic1=cylic1->next;
 if (p==cylic1) return 0;
  }
}


Node* testCylic(Node* h1)
{
Node* p1=h1,*p2=h1;
while (p2!=NULL&&p2->next!=NULL)
{
p1=p1->next;
p2=p2->next->next;
if (p1==p2)
   return p1;
}
return NULL;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值