https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

题目描述

输入两个链表,找出它们的第一个公共结点。

 

代码:

注意:没有检测环状链表。
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
    int getLen(ListNode* p) {
        int ret = 0;
        while (p != NULL) {
            ++ret;
            p = p->next;
        }
        return ret;
    }
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if (pHead1 == NULL || pHead2 == NULL) return NULL;
        int len1 = getLen(pHead1), len2 = getLen(pHead2);
        
        ListNode* p1 = pHead1;
        ListNode* p2 = pHead2;
        if (len1 < len2) {
            int tmp = len1;
            len1 = len2;
            len2 = tmp;
            
            ListNode* ltmp = p1;
            p1 = p2;
            p2 = ltmp;
        }
        
        for (int i=0; i<len1-len2; ++i) {
            p1 = p1->next;
        }
        
        while (p1 != NULL && p2 != NULL && p1 != p2) {
            p1 = p1->next;
            p2 = p2->next;
        }
        
        if (p1 == p2) return p1;
        else return NULL;
    }
};