struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
struct ListNode *tmp1 = headA;
struct ListNode *tmp2 = headB;
while (tmp1 != tmp2) {
if (tmp1->next == NULL) { //超时
tmp1 = headB;
} else {
tmp1 = tmp1->next;
}
if (tmp2->next == NULL) {
tmp2 = headA;
} else {
tmp2 = tmp2->next;
}
}
return tmp1;
}
下面代码正常运行,为什么呢?
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
struct ListNode *tmp1 = headA;
struct ListNode *tmp2 = headB;
while (tmp1 != tmp2) {
if (tmp1 == NULL) { //为什么这里if (tmp1->next == NULL) 会超时?
tmp1 = headB;
} else {
tmp1 = tmp1->next;
}
if (tmp2 == NULL) {
tmp2 = headA;
} else {
tmp2 = tmp2->next;
}
}
return tmp1;
}