力扣刷题 面试题 02.07. 链表相交--day4
题目分析
这道题相对简单, 注意找到指针相等的节点。
先要预处理这两个链表, 使其长度一样
解法
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
int size1 = 0, size2 = 0;
ListNode *temp = headA;
while (temp)
{
size1++;
temp = temp->next;
}
temp = headB;
while (temp)
{
size2++;
temp = temp->next;
}
if (size1 > size2)
{
for (int i = 0; i < size1 - size2; i++)
{
headA = headA->next;
}
}
else if (size1 < size2)
{
for (int i = 0; i < size2 - size1; i++)
{
headB = headB->next;
}
}
while (headA && headB)
{
if (headA == headB)
{
return headA;
}
headA = headA->next;
headB = headB->next;
}
return nullptr;
}
标签:02,面试题,size1,temp,size2,next,headB,headA
From: https://www.cnblogs.com/jianchuxin/p/17347945.html