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

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

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

全部评论

相关推荐

shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务