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

题目描述

输入两个链表,找出它们的第一个公共结点。

解题思路:

遇到这种题目,瞬间想到HashMap…

用一个HashMap依次记录第一个链表的结点;
遍历第二个链表结点,一旦在HashMap中找到,直接输出。
就是这么简单粗暴无脑。

类似的题目还有 两个字符串 找到第一个相同的字符等等,用HashMap特别好解的题目有一下这些:(不定期补充)
剑指offer_第一个只出现一次的字符

剑指offer_数组中出现次数超过一半的数字

当然啦,这是链表,当然有专属这道题的做法。
如果存在公共节点 ,那么他们公共结点之后的全部结点都相同,是吧。先遍历出两个链表的长度,然后让长的先走两个链表的长度差,然后再一起走,这样他们就可以一起牵手走到尾结点。。。。
从他们一起走开始,一旦结点相同,则返回该结点。

HashMap解法代码:

import java.util.*;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
       if (pHead1 == null||pHead2 == null) {
            return null;
        }
        HashMap<ListNode, Integer> map = new HashMap<ListNode, Integer>();
        ListNode current1 = pHead1;
        while (current1 != null) {
            map.put(current1, null);
            current1 = current1.next;
        }
        ListNode current2 = pHead2;
        while (current2 != null) {
            if (map.containsKey(current2))
                return current2;
            current2 = current2.next;
        }
        return null;
    }
}

链表解法:

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
       if (pHead1 == null||pHead2 == null) {
            return null;
        }
        int count1 = 0;
        ListNode p1 = pHead1;
        while (p1!=null){
            p1 = p1.next;
            count1++;
        }
        int count2 = 0;
        ListNode p2 = pHead2;
        while (p2!=null){
            p2 = p2.next;
            count2++;
        }
        int flag = count1 - count2;
        if (flag > 0){
            while (flag>0){
                pHead1 = pHead1.next;
                flag --;
            }
        while (pHead1!=pHead2){
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return pHead1;
    }
        if (flag <= 0){
            while (flag<0){
                pHead2 = pHead2.next;
                flag ++;
            }
            while (pHead1 != pHead2){
                pHead2 = pHead2.next;
                pHead1 = pHead1.next;
            }
            return pHead1;
        }
        return null;
    }
}

测试了两段代码,实际情况如下:

这里写图片描述

还是HashMap大法好,简单无脑

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值