0
点赞
收藏
分享

微信扫一扫

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

读思意行 2022-03-11 阅读 29

文章目录


原题题目


在这里插入图片描述


代码实现(首刷自解)


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
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;
    }
};
举报

相关推荐

0 条评论