0
点赞
收藏
分享

微信扫一扫

IDEA:配置Serializable class without ‘serialVersionUID’ 找不到

芷兮离离 2024-12-02 阅读 2

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一开始以为是比较值相同,结果错了。。。

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    Set<ListNode> visited = new HashSet<ListNode>();
    ListNode temp = headA;
    while (temp != null) {
        visited.add(temp);
        temp = temp.next;
    }
    temp = headB;
    while (temp != null) {
        if (visited.contains(temp)) {
            return temp;
        }
        temp = temp.next;
    }
    return null;
}

在这里插入图片描述

public class Solution {
     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode p = headA, q = headB;
        while (p != q) {
            p = p == null ? headB : p.next;
            q = q == null ? headA : q.next;
        }
        return p;
    }
}

在这里插入图片描述
官方题解

举报

相关推荐

0 条评论