剑指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大法好,简单无脑

posted on 2016-10-05 14:42  gerhold123  阅读(113)  评论(0编辑  收藏  举报