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

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

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

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

/**
 *
 * @param pHead1 ListNode类
 * @param pHead2 ListNode类
 * @return ListNode类
 */
int GetListLength(struct ListNode* head) {
    if (head == NULL)
        return 0;
    int len = 0;
    while (head != NULL) {
        len++;
        head = head->next;
    }
    return len;
}
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1,
                                     struct ListNode* pHead2 ) {
    // write code here
    int len1 = GetListLength(pHead1);
    int len2 = GetListLength(pHead2);
    if (len1 > len2) {
        int sub = len1 - len2;
        while (pHead1 && sub--)
            pHead1 = pHead1->next;
    } else {
        int sub = len2 - len1;
        while (pHead2 && sub--)
            pHead2 = pHead2->next;
    }
    while (pHead1 != pHead2) {
        pHead1 = pHead1->next;
        pHead2 = pHead2->next;
    }
    return pHead1;
}

全部评论

相关推荐

昨天 11:08
门头沟学院 Java
投递京东等公司9个岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
榕城小榕树:你是我见过最幸福的牛客男孩
点赞 评论 收藏
分享
点赞 评论 收藏
分享
水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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