leetCode #160 Intersection of Two Linked Lists

题目 :找到2个链表的交叉点


分析:对2链表而言,若交叉,则必定末尾一个结点相同。故可以此判断交叉点的存在。而对于找到交叉点的 具体位置,若一一比较,需要O(m*n)的复杂度。考虑到交叉链表尾端相同,仅前端不同,可以让长链表先走它多余的长度,随后2链表一起走,即可保证同时到达交点。


答案:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
  if (headA == NULL || headB == NULL)
   return NULL;
  // length of a
  ListNode *curra =  headA;
  int lenA = 1;
  while ( curra->next)
  {
   lenA ++;
   curra = curra->next;
  }
  // length of b
  ListNode *currb =  headB;
  int lenB = 1;
  while ( currb->next)
  {
   lenB ++;
   currb = currb->next;
  }
  // if intersected
  if (curra != currb)
   return NULL;
  ListNode *ha = headA; 
        ListNode *hb = headB; 

  // cancle the distance
  int dis = lenA - lenB;
  if (dis > 0) //A go dis
  {
   while(dis)
   {
    ha = ha->next;
    dis --;
   }
  }
  else // b go
  {
   dis = - dis;
   while(dis)
   {
    hb = hb->next;
    dis --;
   }
  }
  // go to the intersection
  while (ha)
  {
   if (ha == hb)
    return ha;
   else
   {
    ha = ha->next;
    hb = hb->next;
   }

  }
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值