算法6— 判断两个链表是否相交

问题:

给出两个单向链表的头指针,比如h1、h2,判断链表是否相交,如果不相交返回NULL;如果相交,返回指向第一个相交节点的指针。时间复杂度控制在O(n)。

分析:

如果两单向链表相交的话,一定是Y型相交,不可能出现X型,弄清楚这点后接下来的工作就是:
(1)先找到h1,h2的最后一个节点L1和L2,同时记录节点数量a,b;(这里假设 a > b)
(2)判断最后一个节点是否相同;
如果不相同则没相交;
如果相同,则从第一个节点 (短链表) 和 第 |a-b|+1个节点 (长链表)开始比较 (这样,两个链表的指针到相交点的距离是一样的),看是否相等,不相等就寻找下一个节点直到找到交叉点。

代码如下:

[java]  view plain  copy
  1. class Node {  
  2.     char value;  
  3.     Node next;  
  4. }  
[java]  view plain  copy
  1. Node intersect(Node h1, Node h2) {  
  2.     // l1 and l2 refer to the last nodes in the two lists.  
  3.     // a and b refer to the length of the lists.  
  4.     Node l1 = h1;  
  5.     int a = 1;  
  6.       
  7.     Node l2 = h2;  
  8.     int b = 1;  
  9.       
  10.     while (l1.next != null) {  
  11.         l1 = l1.next;  
  12.         a++;  
  13.     }  
  14.       
  15.     while (l2.next != null) {  
  16.         l2 = l2.next;  
  17.         b++;  
  18.     }   
  19.     // no intersection  
  20.     if (l1 != l2) {  
  21.         return null;  
  22.     }   
  23.     //move the pointer of the longer list.  
  24.     for (int i = 0; i < Math.abs(a - b); i++) {  
  25.         if (a > b) {           
  26.             h1 = h1.next;  
  27.         } else {  
  28.             h2 = h2.next;  
  29.         }     
  30.     }  
  31.       
  32.     while (h1 != h2) {  
  33.         h1 = h1.next;  
  34.         h2 = h2.next;  
  35.     }  
  36.       
  37.     return h1;  
  38. }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值