class Solution {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pB;
}
//该测试用例只能覆盖有本来就有相交部分的情况,如果本来不想交的情况,会报空指针异常。比如[1,2.3]和[4,5]
public static void main(String[] args) {
//定义相交后的链表C
ListNode C = new ListNode(3);
C.next = new ListNode(4);
//定义原有链表A,并且将A和C拼接上
ListNode A = new ListNode(1);
A.next = new ListNode(2);
A.next.next = C;
//定义原有链表B,并且把B和C拼接上
ListNode B = new ListNode(5);
B.next = C;
System.out.println(getIntersectionNode(A, B).val);
}
}
无相交的情况,方法getIntersectionNode的返回值为null,所以抛出空指针异常
你可以先判断方法getIntersectionNode的返回值,不为空输出值,为空输出该值为空