链表创建及使用有无错误,只须看链表部分


struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB){
    int n=0;
    int m=0;
    struct ListNode *a=headA;
    struct ListNode *b=headA;
    for(;a->next!=NULL ;n++){
        a=a->next ;
    }
    for(;b->next!=NULL ;m++){
        b=b->next ;
    }
    int A[n];
    int B[m];
    struct ListNode *a1=headA;
    struct ListNode *b1=headB;
    for(int i=0;iA[n-i-1]=a1->next->val ;
        a1=a1->next ;
    }
    for(int i=0;iB[m-i-1]=b1->next->val ;
        b1=b1->next ;
    }
    struct ListNode *tmp;
    int o=0;
    for(int i=0;iif(A[i]==B[i])o++;
    }
    for(int i=0;inext = (struct ListNode*)malloc(sizeof(struct ListNode));
        tmp->next->val = A[o-1-i];
        tmp->next->next = NULL;
        tmp = tmp->next;    
        }
        return tmp;
};

错误太多了,刚开始的指针赋值b = pHeadA应该是b=pHeadB;
遍历链表的for循环,条件应该是 a !=NULL 和 b!=NULL
后面tmp没有初始化就直接使用了
错误不少,不一一说了,修改后运行结果:

img

函数代码:


struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
    int n = 0;
    int m = 0;
    struct ListNode* a = headA;
    struct ListNode* b = headB;  //修改
    for (; a != NULL; n++) {  //修改
        a = a->next;
    }
    for (; b != NULL; m++) {  //修改
        b = b->next;
    }
    int A[n];
    int B[m];
    struct ListNode* a1 = headA;
    struct ListNode* b1 = headB;
    for (int i = 0; i < n; i++) {
        A[n - i - 1] = a1->val;  //修改
        a1 = a1->next;
    }
    for (int i = 0; i < m; i++) {
        B[m - i - 1] = b1->val; //修改
        b1 = b1->next;
    }
    struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode)); //修改
    struct ListNode* pp = tmp; //增加
    tmp->next = NULL; //增加
    int o = 0;
    for (int i = n-1, j=m-1; i >= 0 && j>=0; i--,j--) { //修改
        if (A[i] == B[i])o++;
    }
    for (int i = 0; i < o; i++) {
        tmp->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        tmp->next->val = A[n-o-i+1];
        tmp->next->next = NULL;
        tmp = tmp->next;
    }
    return pp->next; //修改
};


这也没办法编译吧,不都采纳过了么。a和b都是有固定头结点的链表吗?
for(int i=0;i<n;i++){
if(A[i]==B[i])o++;
}
这个有问题啊,如果m<n的话,B[i]就越界访问了
======
struct ListNode tmp; 没有分配空间啊,下面循环你就直接temp->next了啊,必死啊
========
for(int i=0;i<n;i++){
if(A[i]==B[i])o++;
}
for(int i=0;i<o;i++){
tmp->next = (struct ListNode
)malloc(sizeof(struct ListNode));
tmp->next->val = A[o-1-i];
tmp->next->next = NULL;
tmp = tmp->next;
}
这逻辑好奇怪,o只是表示A和B中对应下标值相同的数的数量,但tmp链表却是取A数组中倒数o个数形成链表,这算啥逻辑关系?

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632