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

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

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;
        }
}
全部评论

相关推荐

喜欢飞来飞去的雪碧在刷代码:可以试一试字节
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 20:55
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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