先要想到A + B = B + A
所以用双指针很快就可以得到答案
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
ListNode tA = headA, tB = headB;
int k = 1;
while(tA != tB){
if(tA.next == null){
if(k == 0)
return null;
k = 0;
tA = headB;
}
else
tA = tA.next;
if(tB.next == null)
tB = headA;
else
tB = tB.next;
}
return tA;
}
}
在上面的代码中我们用了额外的代码保证当不存在相交节点时能够返回null
但事实上并不需要这么做,要知道null 是等于 null 的,所以就算两个不相交的链表当双指针重复遍历一次后最终也会交于 null 节点,由此跳出循环
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode cur1 = headA;
ListNode cur2 = headB;
while (cur1 != cur2) {
cur1 = cur1 == null ? headB : cur1.next;
cur2 = cur2 == null ? headA : cur2.next;
}
return cur1;
}
}