您的位置:首页 > 编程语言

编程之美——判断两个链表是否相交

2012-12-14 17:27 211 查看
编程之美——判断两个链表是否相交

问题:给出两个单向链表的头指针,判断这两个链表是否相交,这两个链表可能有环。
分析:具体见《编程之美》
测试程序:
#include "iostream"

using namespace std;

struct Node

{

  int data;

  Node *next;

};

//判断是否有环,返回bool,如果有环,返回环里的节点。

bool isCircle(Node *head,Node* &circleNode,Node* &lastNode)

{

  Node *fast=head->next;

  Node *slow=head;

  while(fast!=slow&&slow&&fast)

  {

    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(slow==fast&&slow&&fast)

  {

    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);

  cout<<isCircle1<<endl;

  cout<<isCircle2<<endl;
  //一个有环,一个无环

  if(isCircle1!=isCircle2)
 return false;
  //两个都无环,判断最后一个节点是否相等

  else if(!isCircle1 && !isCircle2)

  {

    return lastNode1==lastNode2;

  }
 //两个都有环,判断环里的节点是否能到达另一个链表环里的节点

  else

  {

    Node *temp=circleNode1;
while(temp!=circleNode2)
{
 if(temp==circleNode2)
 return true;
 temp=temp->next;
}
return false;

  }

  return false;

}

int main()

{

  Node *n1=new Node();

  Node *n2=new Node();

  Node *n3=new Node();

  Node *n4=new Node();

  n1->data=1;

  n2->data=2;

  n3->data=3;

  n4->data=4;

  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->data=1;

  n6->data=2;

  n7->data=3;

  n8->data=4;

  n5->next = n6;

  n6->next = n7;

  n7->next = n8;

  n8->next = NULL;

  if(detect(n1,n2))
 cout<<"相交"<<endl;

  else
 cout<<"不相交"<<endl;

  return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: