这是一道补课,兼智力开发题。从最优解法中要学到以下几点:
1. 如果有相同节点链,必定存在相同结尾节点,用此可以判断最后是否存在相同节点:
if (tailA != null && tailB != null && tailA != tailB) {
return null;
}
2. 如果存在相同节点,且长度不同,当一个链到尾部,交换链,当另一条链到尾部,再交换,此时,两条链的指针都距离尾部相同的距离,于是可以同时前进,必能找到相同的节点。
if (p1 == null) {
p1 = headB;
}
if (p2 == null) {
p2 = headA;
}
3. 因为用了死循环,这个根本到不了。
//return null;
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode p1 = headA;
ListNode p2 = headB;
ListNode tailA = null;
ListNode tailB = null;
while (true) {
if (p1 == null) {
p1 = headB;
}
if (p2 == null) {
p2 = headA;
}
if (p1.next == null) {
tailA = p1;
}
if (p2.next == null) {
tailB = p2;
}
if (tailA != null && tailB != null && tailA != tailB) {
return null;
}
if (p1 == p2) {
return p1;
}
p1 = p1.next;
p2 = p2.next;
}
//return null;
}