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

来源:互联网 发布:程序员 架构师 编辑:程序博客网 时间:2024/05/29 11:23
/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {        ListNode * p = pHead1;        int num1 = 0;        int num2 = 0;        while (p)            {                num1++;                p = p->next;        }        ListNode *p2 = pHead2;        while(p2)            {                num2++;                p2 = p2->next;        }        if (num2>num1)            {                int x = num2-num1;                for ( int i = 0 ; i!=x ; i++)                    {                        pHead2=pHead2->next;                }                while (pHead2)                    {                        if (pHead2->val == pHead1->val)                            return pHead2;                        pHead2 = pHead2->next;                        pHead1 = pHead1->next;                }        }else{            int x = num1 - num2;            for (int i = 0; i!= x;i++)                {                pHead1 = pHead1->next;            }            while (pHead1)                {                if (pHead1->val == pHead2->val)                    return pHead1;                pHead1 = pHead1->next;                pHead2 = pHead2->next;            }        }        return NULL;    }};
阅读全文
0 0