JAVA: 两个链表的第一个公共结点

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

分析:

解法一:利用hashmap的特性。

import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
         ListNode current1=pHead1;
        ListNode current2=pHead2;
        HashMap<ListNode,Integer> hashMap=new HashMap<>();
        while(current1!=null){
            hashMap.put(current1,null);
            current1=current1.next;
        }
        while(current2!=null){
            if(hashMap.containsKey(current2)){
                return current2;
            }
            current2=current2.next;
        }
        return null;
    }
}
解法二:分别遍历两链表得到它们的长度,就能知道那个链表更长。在第二次遍历时,在较长的链表上线走长度差值步,接着再同时出发遍历,直到找到第一个共同结点。
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int len1=getlistLength(pHead1);
        int len2=getlistLength(pHead2);
        if(len1<=0||len2<=0||pHead1==null||pHead2==null){
            return null;
        }
        int diff=len1-len2;
        ListNode PlistHeadLong=pHead1;
        ListNode PlistHeadShort=pHead2;
        if(len2>len1){
            PlistHeadLong=pHead2;
            PlistHeadShort=pHead1;
            diff=len2-len1;
        }
        //长的链表先走diff步
        while(diff>0){
            PlistHeadLong=PlistHeadLong.next;
            diff--;
        }

        while((PlistHeadLong!=null)&&(PlistHeadShort!=null)&&(PlistHeadLong!=PlistHeadShort)){
            PlistHeadLong=PlistHeadLong.next;
            PlistHeadShort=PlistHeadShort.next;
        }
        ListNode firstCommonNode=PlistHeadLong;
        return firstCommonNode;

    }

    public int getlistLength(ListNode pHead){
        int length=0;
        ListNode pNode=pHead;
        while(pHead!=null){
            length++;
            pHead=pHead.next;
        }
        return length;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值