链表面试题~合并两个有序的单链表

题目:输入两个链表,找出它们的第一个公共结点。
首先我们看到这个题,首先会想到的的方法是蛮力法,也就是逐个遍历链表1中的节点,再与链表2中的每一个节点进行逐一比较,显然这种办法并不是一个好办法。
这里写图片描述
两个链表都是有序的,我们可以通过遍历两个链表,分别求出两个链表的长度以及他们的长度之差,第二部遍历的时候,先让长的链表走两个链表之差步,然后两个链表同时走,走到两个链表的交点时,两个链表就会指向同一个数据。
下面用代码实现相关操作

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};

ListNode* FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2) {
    int len1 = 0, len2 = 0;
    int sublen = 0;
    ListNode* temp1 = pHead1;
    ListNode* temp2 = pHead2;

    if (pHead1 == NULL || pHead2 == NULL)
        return NULL;

    //求两个链表的长度 
    while (temp1)
    {
        len1++;
        temp1 = temp1->next;
    }

    while (temp2)
    {
        len2++;
        temp2 = temp2->next;
    }

    temp1 = pHead1;
    temp2 = pHead2;
    // 判断两个链表哪个比较长 
    if (len1 > len2)
    {
        sublen = len1 - len2;
        while (sublen--)
        {
            temp1 = temp1->next;
        }
    }
    else if (len2 > len1)
    {
        sublen = len2 - len1;
        while (sublen--)
        {
            temp2 = temp2->next;
        }
    }

    // 找公共节点 
    while (temp1 != NULL)
    {
        if (temp1 == temp2)
            break;
        temp1 = temp1->next;
        temp2 = temp2->next;
    }

    return temp1;
}

猜你喜欢

转载自blog.csdn.net/wyn126/article/details/81383411