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);
}
}

leetcode-160 链表相交,无相交的情况怎么写测试用例
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- IT-猕猴桃 2021-02-10 15:22关注
无相交的情况,方法getIntersectionNode的返回值为null,所以抛出空指针异常
你可以先判断方法getIntersectionNode的返回值,不为空输出值,为空输出该值为空
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报