NC66 两个链表的第一个公共结点

[https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=188&&tqId=38581&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking]

bool f(struct ListNode* a,struct ListNode* b){//为什么要设置函数,因为当两个书相等的时候还要看后面的是否相等
    while(a&&b){
        if(a->val!=b->val)
            return false;
        a=a->next;
        b=b->next;
    }
    if(a==NULL&&b!=NULL)//次情况是没结束只是中途值相同
        return false;
    else if(a!=NULL&&b==NULL)
        return false;
    else
    return true;
}
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    for(struct ListNode* a=pHead1; a!=NULL; a=a->next){
        for(struct ListNode* b=pHead2;b!=NULL;b=b->next){
            if(b->val==a->val){
               if(f(a,b))
                return a;
            }
        }
    }
    return NULL;
}

方法二

/*此方法是相当于把两个链表长度变成一样a+b=b+a*/
/*如a 1 2 3
b 2 3
最终因为长度不一样
最终变成一样的此处有省略
a 1 2 3 2 3
b 2 3 1 2 3
最终在2 3 停止
*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        ListNode *ta = pHead1, *tb = pHead2;
        while (ta != tb) {//两种一种是最后为空,此处的最后是a+b的长度最后,这里的判断有点东西,是内存地址的判断,开始不明白以为是值
            ta = ta ? ta->next : pHead2;
            tb = tb ? tb->next : pHead1;
        }
        return ta;
    }
};
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    for(struct ListNode* a=pHead1; a!=NULL; a=a->next){//收到上面的启发,直接指针判断是不是同一个地址
        for(struct ListNode* b=pHead2;b!=NULL;b=b->next){
            if(b==a){
                return a;
            }
        }
    }
    return NULL;
}
上一篇:student


下一篇:对于SQL Server 2008删除或压缩数据库日志的方法