剑指offer:两个链表的第一个公共结点

来源:互联网 发布:网络推广类的书籍 编辑:程序博客网 时间:2024/05/19 15:19

题目描述

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

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2) {        if (pHead1 == NULL || pHead2 == NULL){            return NULL;        }        int len1 = 0, len2 = 0;        ListNode *p1 = pHead1;        ListNode *p2 = pHead2;        while (p1){            len1++;            p1 = p1->next;        }        while (p2){            len2++;            p2 = p2->next;        }        p1 = pHead1, p2 = pHead2;        if (len1 > len2){            int more = len1 - len2;            while (more--){                p1 = p1->next;            }        }        else if (len1 < len2){            int more = len2 - len1;            while (more--){                p2 = p2->next;            }        }        ListNode *common;        while (p1!= p2){            p1 = p1->next;            p2 = p2->next;        }        common = p1;        return common;    }};
0 0