牛客:剑指offer:两个链表的第一个公共结点(Java)

题目:

看到这个题,我想到的就是最笨的办法,先遍历两个链表,算出各自的长度,然后让长的链表先走Math.abs(l1-l2)步,然后两个指针再一起走,当指向同一个节点时就找到了公共节点。

虽然觉得这个办法太老了,但是暂时也没有想到新方法。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
 		if(pHead1 == null || pHead2 == null)
            return null;
        int l1 = getLen(pHead1);
        int l2 = getLen(pHead2);
        if(l1 > l2)
            return getCon(pHead1,pHead2,l1-l2);
        return getCon(pHead2,pHead1,l2-l1);
    }
    public int getLen(ListNode tmp){
        int res = 0;
        while(tmp != null){
            res++;
            tmp = tmp.next;
        }
        return res;
    }
    public ListNode getCon(ListNode p1,ListNode p2,int len){
        for(int i = 0; i < len; i++){
            p1 = p1.next;
        }
        while(p1 != null && p2 != null){
            if(p1.val == p2.val)
                return p1;
            p1 = p1.next;
            p2 = p2.next;
        }
        return null;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值