题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    struct ListNode* first = pHead2; //保存链表2的头结点地址
    while(pHead1)
    {
        while(pHead2)
        {
            if(pHead2->val == pHead1->val)
            {
                if((pHead1->next == NULL&&pHead2->next == NULL)||(pHead1->next!=NULL&&pHead2->next!=NULL&&pHead1->next->val == pHead2->next->val)) //找到第一个公共结点
                {
                    return pHead1;
                }
            }
            pHead2 = pHead2->next;
        }
        pHead1 = pHead1->next;
        pHead2 = first;
    }
    return NULL;
}

全部评论

相关推荐

好奇的伊登准备进厂:找了两个多月沟通六千多,不到十个面试至今仍未找到实习,看完你还想坚持下去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务