剑指两个链表的第一个公共结点

  • 要明确一点的是,两个链表如果相交的话,那么从相交的第一个结点往后,这两个链表会是这样子滴:

为啥呢?如果链表相交的话,说明各自链表的当前结点的信息是完完全全是一样的,比如这个结点的结构是这样子滴{ Node next, int val},next指针一样,val值一样,所以,第一个相交结点的结点就汇成了一条了,像个倒y。

  • 可以先求下各自链表的长度,就上面的图举个例子,长的那个l1, 短的那个l2, l1.size - l2.size刚好就是长的那条比短的那条读出来的长度,长的先走完这个长度差,就可以跟短的那个链表从同一起点同时开始遍历比较每个结点啦。只要有相同的,就说明找到第一个相交的结点啦!
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
       
        if(pHead1 == null || pHead2 == null)
            return null;
        int size_1 = getSize(pHead1);
        int size_2 = getSize(pHead2);
        int dif = 0;
       
        if(size_1 > size_2){
          dif = size_1 - size_2;
           pHead1 = walk(pHead1,dif);
        }else{
           dif = size_2 - size_1;
            pHead2 = walk(pHead2, dif);
        }
        while(pHead1 != null){
             if(pHead1 == pHead2)
                 return pHead1;
              pHead1 = pHead1.next;
              pHead2 = pHead2.next;
           
        }
        return null;
    }
    private ListNode  walk(ListNode head, int dif){
       while(dif > 0){
           head = head.next;
           dif --;
       }
        return head;
    }
    private int getSize(ListNode head){
        if(head == null)
            return 0;
        ListNode cur = head;
        int cnt = 0;
        while(cur != null){
            cur = cur.next;
            cnt++;
        }
      return cnt;       
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值