面试题:两个链表的第一个公共节点

题目描述:输入两个链表,找出它们的第一个公共结点。

思路1:使用HashMap很多判断重复的题都可以用HashMap

import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode node1=pHead1;
        ListNode node2=pHead2;
        HashMap<ListNode,Integer> map=new HashMap<ListNode,Integer>();
        while(node1!=null){
            map.put(node1,null);
            node1=node1.next;
        }
        //判断Map中是否包含指定的键名
        while(node2!=null){
            if(map.containsKey(node2))  return node2;
            node2=node2.next;
        }
        return null;
    }
}

思路2:遍历两个链表的长度 其中一个多走k步

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode node1=pHead1;
        ListNode node2=pHead2;
        int length1=getLength(node1);
        int length2=getLength(node2);
        if(length1==0||length2==0) return null;
        if(length1>length2){
            int len=length1-length2;
            while(len>0){
                len--;
                node1=node1.next;
            }
        }else{
            int len=length2-length1;
            while(len>0){
                len--;
                node2=node2.next;
            }
        }
        while(node1!=node2){
            node1=node1.next;
            node2=node2.next;
        }
        return node1;
    }
    public int getLength(ListNode head){
        if(head==null) return 0;
        int length=0;
        while(head!=null){
            length++;
            head=head.next;
        }
        return length;
    }
}
原文地址:https://www.cnblogs.com/Aaron12/p/9540802.html