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

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

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;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-26 14:50
人力小鱼姐:有后面墨迹那两句的时间问题早回答完了
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
明天不下雨了_人机版:让我们大声的说出来:以前的未来就是现在
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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