查询两个链表的公共节点

时间:2021-03-16 13:39:17   收藏:0   阅读:0

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

如下面的两个链表:

 技术图片

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    int GetNumsOfList(ListNode* headA) {
        int nums = 0;
        while (headA != NULL) {
            ++nums;
            headA = headA->next;
        }
        return nums;
    }

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int numsA = GetNumsOfList(headA);
        int numsB = GetNumsOfList(headB);
        ListNode* B = headB;
        ListNode* A = headA;
        if (numsB > numsA) {
            int diff = numsB - numsA;
            while (diff --) {
                B = B->next;
            }
        } else if (numsA > numsB) {
            int diff = numsA - numsB;
            while (diff --) {
                A = A->next;
            }
        }
        while (A && B) {
            if (A==B) {
                return A;
            }
            A = A->next;
            B = B->next;
        }
        return NULL;
    }
};

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!