欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

剑指offer——面试题37:两个链表的第一个公共结点

程序员文章站 2022-07-14 14:50:03
...

剑指offer——面试题37:两个链表的第一个公共结点

20180906整理

Solution1:

时间复杂度为O(n2)的垃圾算法

/*
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 == pHead2)
            return pHead2;
        else {
            struct ListNode *tempNode1 = pHead1, *tempNode2 = pHead2;
            while(tempNode1 != NULL){
                tempNode2 = pHead2;
                while(tempNode2 != NULL){
                    if(tempNode1 == tempNode2)
                        return tempNode1;
                    tempNode2 = tempNode2->next;
                }
                tempNode1 = tempNode1->next;
            }
            return NULL;
        }
    }
};

Solution2:

书上写的是先找出两个链表的长度,然后长链表先走长度差步的方法也可以。
【重点掌握算法】

/*
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 || !pHead2) return NULL;
        ListNode *cur1 = pHead1, *cur2 = pHead2;
        int nums1 = 0, nums2 = 0, diff = 0;
        while (cur1) {
            nums1++;
            cur1 = cur1->next;
        }
        while (cur2) {
            nums2++;
            cur2 = cur2->next;
        }
        diff = abs(nums1 - nums2);
        //置位
        cur1 = pHead1;cur2 = pHead2;
        if (nums1 > nums2) { //子串1while (diff--)
                cur1 = cur1->next;
        } else { //子串2while (diff--)
                cur2 = cur2->next;
        }
        while (cur1 != cur2) {
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        return cur1;
    }
};

Solution3:

20180906更:真是sao出水了来了
下面这个代码比较吊。。
风骚走位,叹为观止,自叹弗如,自叹弗如~~~~
其思想是俩指针通过多走一遍线路形成闭环来抵消掉两个链表的长度差,真是聪明啊~
如下图所示,一目了然:
剑指offer——面试题37:两个链表的第一个公共结点
图咋这么大。。。
参考网址:https://www.nowcoder.com/profile/3017991/codeBookDetail?submissionId=19005908

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
        ListNode *p1 = pHead1;
        ListNode *p2 = pHead2;
        while(p1!=p2){
            p1 = (p1==NULL ? pHead2 : p1->next);
            p2 = (p2==NULL ? pHead1 : p2->next);
        }
        return p1;
    }
};