东莞病毒站长工具seo综合查询广告
分别让tmp1以及tmp2的结点分别先指向headA以及headB,当遍历完成后,再让tmp1以及tmp2分别指向haedB和headA反转
此处有个问题:为什么if判断句中写tmp1!=nullptr,能够编译通过,但是写tmp1->next=nullptr就不能编译通过,显示超出时间限制呢?
正确代码:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//判断是否为空指针
if (headA == nullptr || headB == nullptr)
{
return nullptr;
}
ListNode *p1 = headA, *p2 = headB;
//比较两个结点在走过相同路径后 对应的结点的值是否相等
while(p1!=p2)
{
if(p1 !=nullptr)
{
p1 = p1->next;
}
else
{
p1 = headB;
}
if(p2!= nullptr)
{
p2 = p2->next;
}
else
{
p2 = headA;
}
}
return p1;
}
};
错误代码(显示超出时间限制)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//判断是否为空指针
if (headA == nullptr || headB == nullptr)
{
return nullptr;
}
ListNode *p1 = headA, *p2 = headB;
//比较两个结点在走过相同路径后 对应的结点的值是否相等
while(p1!=p2)
{
if(p1->next !=nullptr)
{
p1 = p1->next;
}
else
{
p1 = headB;
}
if(p2->next!= nullptr)
{
p2 = p2->next;
}
else
{
p2 = headA;
}
}
return p1;
}
};