两个链表交点查找代码LeetCode测试通过但本地IDE运行报空指针错误排查
Hey there! Let's break down what's happening here. Your core logic for finding the intersection of two linked lists is totally correct—hence why it passes all LeetCode test cases. The problem lies in how you're constructing your local test case, plus a missing safety check before accessing test.val.
1. The Root Cause: No Real Intersection in Your Local Test Case
LeetCode's test cases create linked lists that share the exact same node object at their intersection point (same memory reference). But in your main method, you're creating separate node chains with identical values:
- For
hA, you havenew ListNode(8, new ListNode(4, new ListNode(5))) - For
hB, you have another entirely separatenew ListNode(8, new ListNode(4, new ListNode(5)))
These are two distinct sets of nodes—they have matching values, but different memory addresses. So when your code checks headA == headB, it never finds a match, and returns null. Trying to access test.val when test is null triggers the error you're seeing.
2. Fix the Test Case to Create a Valid Intersection
To replicate LeetCode's valid intersection scenario, create a shared node chain first, then attach it to both hA and hB. Here's how to adjust your main method:
public static void main(String[] args) { // Create the shared intersection segment first ListNode intersection = new ListNode(8, new ListNode(4, new ListNode(5))); // Build list A: 4 -> 1 -> [shared segment] ListNode hA = new ListNode(4, new ListNode(1, intersection)); // Build list B: 5 -> 6 -> 1 -> [shared segment] ListNode hB = new ListNode(5, new ListNode(6, new ListNode(1, intersection))); ListNode test = getIntersectionNode(hA, hB); // Always check for null before accessing node values! if (test != null) { System.out.println(test.val); // This will output 8 as expected } else { System.out.println("No intersection found between the two lists."); } }
3. Add a Null Check for Robustness
Even when you expect an intersection, handling the "no intersection" case prevents crashes. Adding the null check before test.val makes your code resilient to edge cases, just like the version that passes LeetCode's tests.
With these changes, your local run will behave exactly as it does on LeetCode—no more null pointer exceptions!
内容的提问来源于stack exchange,提问作者LCL

