面试算法

牛客-剑指0ffer-两个链表的第一个公共结点

2019-08-06  本文已影响8人  wenyilab

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        int len1 = findlistLength(pHead1);
        int len2 = findlistLength(pHead2);
        if (len1 > len2){
            pHead1 = walk(pHead1,len1-len2);
        }else{
            pHead2 = walk(pHead2,len2-len1);
        }
        while(pHead1 != NULL){
            if (pHead1 == pHead2) return pHead1;
            pHead1 = pHead1->next;
            pHead2 = pHead2->next;
        }
        return NULL;
    }
    int findlistLength(ListNode* pHead1 ){
        if (pHead1 == NULL) return 0;
        int sum = 1;
        while(pHead1 = pHead1->next){
            sum++;
        }
        return sum;
    }
    ListNode* walk(ListNode* pHead1,int step){
        while(step--){
            pHead1 = pHead1->next;
        }
        return pHead1;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读