题解 | #两个链表的第一个公共结点#

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

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

判断两个链表大小,把小链表数据添加到set里,遍历大链表直到出现set里的数据并返回

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

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.*;
public class Solution {
    int  ListLen(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int length1 = ListLen(pHead1), length2 = ListLen(pHead2);
        ListNode res, res2;
        if (length1 < length2) {
            res = pHead1;
            res2 = pHead2;
        } else{
            res2 = pHead1;
            res = pHead2;
        }
        HashSet<ListNode> hSet = new HashSet<>();
        while (res != null) {
            hSet.add(res);
            res = res.next;
        }
        while (res2 != null){
            if(hSet.contains(res2))
                return res2;
            res2 = res2.next;
        }
        return null;
        }
}
全部评论

相关推荐

05-23 19:02
吉林大学 Java
点赞 评论 收藏
分享
墨西哥大灰狼:如果你的校友卤馆还在的话,他肯定会给你建议的,可是卤馆注销了@ 程序员卤馆
点赞 评论 收藏
分享
鼠鼠第一次实习,啥也不懂一直是自己一个人吃的饭,不会做工作老是被嫌弃,大人的世界是这样的吗?
我是星星我会发亮:好的mt有两种,一种愿意教你的,一种几乎什么活都不给你派让你很闲允许你做自己事情的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务