转:链表相交问题 详解

源地址:http://blog.163.com/bbluesnow@126/blog/static/27784545201251051156817/

链表相交问题  

2012-06-10 17:15:37|  分类: 算法 |  标签:微软面试题  |字号 订阅

 
 

1、如何判断一个单链表有环

2、如何判断一个环的入口点在哪里

3、如何知道环的长度

4、如何知道两个单链表(无环)是否相交

5、如果两个单链表(无环)相交,如何知道它们相交的第一个节点是什么?

6、如何知道两个单链表(有环)是否相交

7、如果两个单链表(有环)相交,如何知道它们相交的第一个节点是什么?

 以下进行分析,并在最后附源代码及测试

1、采用快慢步长法。令两个指针p和q分别指向头结点,p每次前进一步,q每次前进两步,如果p和q能重合,则有环。可以这么理解,这种做法相当于p静止不动,q每次前进一步,所有肯定有追上p的时候。

我们注意到,指针pq分别以速度为12前进。如果以其它速度前进是否可以呢?

假设pq分别以速度为v1v2前进。如果有环,设指针pq第一次进入环时,他们相对于环中第一个节点的偏移地址分别为ab(可以把偏移地址理解为节点个数)

这样,可以看出,链表有环的充要条件就是某一次循环时,指针pq的值相等,就是它们相对环中首节点的偏移量相等。我们设环中的结点个数为n,程序循环了m次。

由此可以有下面等式成立:(mod(n)即对n取余)

(a+m*v1)mod(n) = (b+m*v2) mod(n)

设等式左边mod(n)的最大整数为k1,等式右边mod(n)的最大整数为k2,则

(a+m*v1)-k1*n = (b+m*v2)-k2*n

整理以上等式:

m= |((k2-k1)*n+a-b)/( v2-v1)|       

如果是等式①成立,就要使循环次数m为一整数。显然如果v2-v11,则等式成立。

这样pq分别以速度为v1v2|v2-v1|1时,按以上算法就可找出链表中是否有环。当然|v2-v1|不为1时,也可能可以得出符合条件的m。

时间复杂度分析:假设甩尾(在环外)长度为 len1(结点个数),环内长度为 len2,链表总长度为n,则n=len1+len2 。当p步长为1,q步长为2时,p指针到达环入口需要len1时间,p到达入口后,q处于哪里不确定,但是肯定在环内,此时p和q开始追赶,q最长需要len2时间就能追上p(p和q都指向环入口),最短需要1步就能追上p(p指向环入口,q指向环入口的前一个节点)。事实上,每经过一步,q和p的距离就拉近一步,因此,经过q和p的距离步就可以追上p。因此总时间复杂度为O(n),n为链表的总长度。

 

2、分别从链表头和碰撞点,同步地一步一步前进扫描,直到碰撞,此碰撞点即是环的入口。

证明如下:

链表形状类似数字 6 。 

假设甩尾(在环外)长度为 a(结点个数),环内长度为 b 。 

则总长度(也是总结点数)为 a+b 。 

从头开始,0 base 编号。

将第 i 步访问的结点用 S(i) 表示。i = 0, 1 ... 

当 i<a 时,S(i)=i ; 

当 i≥a 时,S(i)=a+(i-a)%b 。

分析追赶过程。 

两个指针分别前进,假定经过 x 步后,碰撞。则有:S(x)=S(2x) 

由环的周期性有:2x=tb+x 。得到 x=tb 。 

另,碰撞时,必须在环内,不可能在甩尾段,有 x>=a 。

连接点为从起点走 a 步,即 S(a)。 

S(a) = S(tb+a) = S(x+a)。 

得到结论:从碰撞点 x 前进 a 步即为连接点。

根据假设易知 S(a-1) 在甩尾段,S(a) 在环上,而 S(x+a) 必然在环上。所以可以发生碰撞。 

而,同为前进 a 步,同为连接点,所以必然发生碰撞。

综上,从 x 点和从起点同步前进,第一个碰撞点就是连接点。

时间复杂度分析:假设甩尾(在环外)长度为 len1(结点个数),环内长度为 len2 。则时间复杂度为“环是否存在的时间复杂度”+O(len1)

 

3、从碰撞点开始,两个指针p和q,q以一步步长前进,q以两步步长前进,到下次碰撞所经过的操作次数即是环的长度。这很好理解,比如两个运动员A和B从起点开始跑步,A的速度是B的两倍,当A跑玩一圈的时候,B刚好跑完两圈,A和B又同时在起点上。此时A跑的长度即相当于环的长度。

假设甩尾(在环外)长度为 len1(结点个数),环内长度为 len2 ,则时间复杂度为“环是否存在的时间复杂度”+O(len2)。

 

4、法一:将链表A的尾节点的next指针指向链表B的头结点,从而构造了一个新链表。问题转化为求这个新链表是否有环的问题。

     时间复杂度为环是否存在的时间复杂度,即O(length(A)+length(B)),使用了两个额外指针

     法二:两个链表相交,则从相交的节点起,其后的所有的节点都是都是两个链表共有的。因此,如果它们相交,则最后一个节点一定是共有的。因此,判断两链表相交的方法是:遍历第一个链表,记住最后一个节点。然后遍历第二个链表,到最后一个节点时和第一个链表的最后一个节点做比较,如果相同,则相交。

     时间复杂度:O(length(A)+length(B)),但是只用了一个额外指针存储最后一个节点

 

5、将链表A的尾节点的next指针指向链表B的头结点,从而构造了一个环。问题转化为求这个环的入口问题。
时间复杂度:求环入口的时间复杂度

 

6、分别判断两个链表A、B是否有环(注,两个有环链表相交是指这个环属于两个链表共有)

如果仅有一个有环,则A、B不可能相交

如果两个都有环,则求出A的环入口,判断其是否在B链表上,如果在,则说明A、B相交。

时间复杂度:“环入口问题的时间复杂度”+O(length(B))

 

7、分别计算出两个链表A、B的长度LA和LB(环的长度和环到入口点长度之和就是链表长度),参照问题3。

如果LA>LB,则链表A指针先走LA-LB,链表B指针再开始走,则两个指针相遇的位置就是相交的第一个节点。

如果LB>LA,则链表B指针先走LB-LA,链表A指针再开始走,则两个指针相遇的位置就是相交的第一个节点。

时间复杂度:O(max(LA,LB))

源码,并没有封装成类,存在某些重复运算

islistJunction.

/******************************************************************************************************
Description   : 检查链表是否有环
Prototype     : template<typename T>
    bool checkCircle(T* head)
Input Param   : head,链表的头结点指针
Output Param  : 无
Return Value  : bool变量,TRUE为有环,FALSE为没有环
********************************************************************************************************/
template<typename T>
bool checkCircle(T* head)
{
 if(NULL == head)
  returnfalse;
 T* low = head;
 T* fast = head;

 while(low->next!= NULL &&(fast->next!= NULL)&&(fast->next)->next!= NULL)
 {
  low = low->next;
  fast =(fast->next)->next;
  if(low == fast)
  {
   returntrue;
  }
 }
 returnfalse;
}

/******************************************************************************************************
Description   : 判断两个链表是否相交
Prototype     : template<typename T>
    bool isListJunction(T* head1,T* head2)
Input Param   : head1,第一个链表的头结点;head2,第二个链表的头结点
Output Param  : 无
Return Value  : bool变量,true为有交集,false为没有交集
********************************************************************************************************/
template<typename T>
bool isListJunction(T* head1,T* head2)
{
 if(NULL == head1 || NULL == head2)
 {
  returnfalse;
 }
 // 如果头结点相同,代表相同的链表,肯定是相交
 if(head1 == head2)
 {
  returntrue;
 }
 
 // 检测是否有环
 bool b1 = checkCircle(head1);
 bool b2 = checkCircle(head2);
 // 若相交,则两个链表要么都无环,要么都有环
 if(b1 != b2)
 {
  returnfalse;
 }
 
 // 若都无环,b1==b2==0,尾节点必然相同,是Y字形
 if(!b1)
 {
  while(head1 != NULL)
  {
   head1 = head1->next;
  }
  while(head2 != NULL)
  {
   head2 = head2->next;
  }
  if(head1 == head2)
  {
   returntrue;
  }
 }

 // 若有环,则找出链表1的环入口,看是否在链表2上
 if(b1)
 {
  T* port = findLoopPort(head1);
  if(port != NULL)
  {
   T* temp = head2;
   int length2 = getLoopLength(head2)+ getTailLength(head2);
   while(port != temp &&(length2--)>=0)
    temp = temp->next;

   if(port == temp)
    returntrue;
   else
    returnfalse;
  }
 }
 
 returnfalse;
}

/******************************************************************************************************
Description   : 判断两个链表是否相交
Prototype     : template<typename T>
    bool isListJunction(T* head1,T* head2)
Input Param   : head1,第一个链表的头结点;head2,第二个链表的头结点
Output Param  : 无
Return Value  : bool变量,true为有交集,false为没有交集
********************************************************************************************************/
template<typename T>
bool isListJunction(T* head1,T* head2,T *&junctionNode)
{
 if(NULL == head1 || NULL == head2)
 {
  returnfalse;
 }
 // 如果头结点相同,代表相同的链表,肯定是相交
 if(head1 == head2)
 {
  junctionNode = head1;
  returntrue;
 }
 
 // 检测是否有环
 bool b1 = checkCircle(head1);
 bool b2 = checkCircle(head2);
 // 若相交,则两个链表要么都无环,要么都有环
 if(b1 != b2)
 {
  returnfalse;
 }
 
 // 若都无环,b1==b2==0,尾节点必然相同,是Y字形
 if(!b1)
 {
  T* node1 = head1;
  T* node2 = head2;
  while(node1 != NULL)
  {
   node1 = node1->next;
  }
  while(node2 != NULL)
  {
   node2 = node2->next;
  }
  if(node1 == node2)
  {
   // 相交,把第一个链表的尾节点指向第二个链表
   node1->next= head2;
   junctionNode = findLoopPort(head1);
   returntrue;
  }
 }

 // 若有环,则找出链表1的环入口,看是否在链表2上
 if(b1)
 {
  int length1 = getLoopLength(head1)+ getTailLength(head1);
  int length2 = getLoopLength(head2)+ getTailLength(head2);
  int len = length2;
  T* port = findLoopPort(head1);
  if(port != NULL)
  {
   T* temp = head2;
   while(port != temp &&(len--)>=0)
    temp = temp->next;

   if(port == temp)
   {
    // 若长度相等,同步寻找相同的节点
    if(length1 == length2)
    {
     while(head1 != head2)
     {
      head1 = head1->next;
      head2 = head2->next;
     }
     junctionNode = head1;
    }
    // 若长度不等,长的先剪掉长度差,然后再同步递增
    elseif(length1 > length2)
    {
     int step = length1 - length2;
     while(step--)
     {
      head1 = head1->next;
     }
     while(head1 != head2)
     {
      head1 = head1->next;
      head2 = head2->next;
     }
     junctionNode = head1;
    }
    else
    {
     int step = length2 - length1;
     while(step--)
     {
      head2 = head2->next;
     }
     while(head1 != head2)
     {
      head1 = head1->next;
      head2 = head2->next;
     }
     junctionNode = head1;
    }
    returntrue;
   }
   else
   {
    returnfalse;
   }
  }
 }
 
 returnfalse;
}

/******************************************************************************************************
Description   : 查找环的入口
Prototype     : template<typename T>
    T* findLoopPort(T* head)
Input Param   : head,链表的头结点
Output Param  : 无
Return Value  : 环入口点的指针
********************************************************************************************************/
template<typename T>
T* findLoopPort(T* head)
{
 // 判断是否有环,五环返回NULL
 checkCircle(head);
 if(!checkCircle(head))
  return NULL;

 T* low = head;
 T* fast = head;

 // low按照步长1增加,fast按照步长2增加,找到碰撞点
 while(1)
 {
  low = low->next;
  fast = fast->next->next;
  if(low == fast)
   break;
 }
 
 // 分别从头结点和碰撞节点开始按照步长1增加,遍历链表,第一个节点相同的点是环入口点
 low = head;
 while(low != fast)
 {
  low = low->next;
  fast = fast->next;
 }

 return low; 
}

/******************************************************************************************************
Description   : 计算环的长度
Prototype     : template<typename T>
    int getLoopLength(T* head)
Input Param   : head,链表的头结点
Output Param  : 无
Return Value  : int,表示长度
********************************************************************************************************/
template<typename T>
int getLoopLength(T* head)
{
 if(!checkCircle(head))
  return0;
 

 T* low = head;
 T* fast = head;
 int length =0;

 // low按照步长1增加,fast按照步长2增加,找到碰撞点,然后接着循环直到下一次碰撞,
 // 计算两次碰撞之间的循环次数即为长度
 while(1)
 {
  low = low->next;
  fast = fast->next->next;
  if(low == fast)
   break;
 }
 while(1)
 {
  low = low->next;
  fast = fast->next->next;
  length++;
  if(low == fast)
   break;

 }
 return length;
}

/******************************************************************************************************
Description   : 计算有环链表的尾长度
Prototype     : template<typename T>
    int getTailLength(T* head)
Input Param   : head,链表的头结点
Output Param  : 无
Return Value  : int,表示长度
********************************************************************************************************/
template<typename T>
int getTailLength(T* head)
{
 T* port = findLoopPort(head);
 int length =0;
 T* temp = head;

 while(temp != port)
 {
  length++;
  temp = temp->next;
 }
 return length;
}

main.cpp

#include"isListJunction.h"
#include<string>

template<typename T>
struct listNode
{
 T val;
 listNode *pre;
 listNode *next;

 listNode()
 {
  pre = NULL;
  next= NULL;
 }

 listNode(T value)
 {
  val = value;
  pre = NULL;
  next= NULL;
 }
};

int main(int argc,char** argv)
{
 string first ="my is";
 string second ="your";
 string three ="is";
 string four ="king";
 string five ="name";
 string first2 ="speak";
 string second2 ="what";

 list<string> firstlist;
 firstlist.push_back(first);
 firstlist.push_back(second);
 firstlist.push_back(three);
 firstlist.push_back(four);
 firstlist.push_back(five);

 list<string> secondlist;
 secondlist.push_back(first2);
 secondlist.push_back(second2);
 secondlist.push_back(four);
 secondlist.push_back(five);

 // 链表1,无环
 listNode<string>*head1 =new listNode<string>(first);
 listNode<string>*pnode2 =new listNode<string>(second);
 head1->next= pnode2;
 listNode<string>*pnode3 =new listNode<string>(three);
 pnode2->next= pnode3;
 listNode<string>*pnode4 =new listNode<string>(four);
 pnode3->next= pnode4;
 listNode<string>*pnode5 =new listNode<string>(five);
 pnode4->next= pnode5;

 // 链表2,无环
 listNode<string>*head2 =new listNode<string>(first2);
 listNode<string>*pnode22 =new listNode<string>(second2);
 head2->next= pnode22;
 pnode22->next= pnode4;
 pnode4->next= pnode5;

 // 链表1、2相交
 bool bJunction = isListJunction(head1,head2);
 std::cout<< bJunction<<std::endl;

 std::cout<< checkCircle(head1)<<endl;
 std::cout<< checkCircle(head2)<<endl;


 string first3 ="1";
 string second3 ="2";
 string three3 ="3";
 string four3 ="4";
 string five3 ="5";
 string six3 ="6";
 string seven3 ="7";

 // 链表3,有环
 listNode<string>*head3 =new listNode<string>(first3);
 listNode<string>*pnode32 =new listNode<string>(second3);
 head3->next= pnode32;
 listNode<string>*pnode33 =new listNode<string>(three3);
 pnode32->next= pnode33;
 listNode<string>*pnode34 =new listNode<string>(four3);
 pnode33->next= pnode34;
 listNode<string>*pnode35 =new listNode<string>(five3);
 pnode34->next= pnode35;
 listNode<string>*pnode36 =new listNode<string>(six3);
 pnode35->next= pnode36;
 pnode36->next= pnode33;

 cout<<findLoopPort(head3)->val<<endl;
 cout<<getLoopLength(head3)<<endl;

 // 链表4,有环
 listNode<string>*head4 =new listNode<string>(seven3);
 head4->next= pnode32;
 cout<<isListJunction(head3,head4)<<endl;

 cout<<"the length of list3 : "<<getLoopLength(head3)+ getTailLength(head3)<<endl;
 cout<<"the length of list4 : "<<getLoopLength(head4)+ getTailLength(head3)<<endl;
 
 listNode<string>*junctionNode =new listNode<string>;
 cout<<isListJunction(head3,head4,junctionNode)<<endl;
 cout<<"list3 与 list4的交点: "<<junctionNode->val<<endl;
 return0;
}

原文地址:https://www.cnblogs.com/xuhj001/p/3389137.html