Leetcode 剑指 Offer 52. 两个链表的第一个公共节点(DAY 257)---- 后端面试题
文章目录
原题题目

代码实现(首刷自解)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* ptr1 = headA,*ptr2 = headB;
while(ptr1 && ptr2)
{
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
ListNode* ptr_next1 = headA,*ptr_next2 = headB;
while(ptr1 || ptr2)
{
if(ptr1)
{
ptr_next1 = ptr_next1->next;
ptr1 = ptr1->next;
}
else
{
ptr_next2 = ptr_next2->next;
ptr2 = ptr2->next;
}
}
while(ptr_next1 && ptr_next2 && ptr_next1 != ptr_next2)
{
ptr_next1 = ptr_next1->next;
ptr_next2 = ptr_next2->next;
}
return ptr_next1;
}
};