LikeHash 2022-12-01 13:47 采纳率: 100%
浏览 26
已结题

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


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;i<n;i++){
        A[n-i-1]=a1->next->val ;
        a1=a1->next ;
    }
    for(int i=0;i<m;i++){
        B[m-i-1]=b1->next->val ;
        b1=b1->next ;
    }
    struct ListNode *tmp;
    int o=0;
    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;    
        }
        return tmp;
};
  • 写回答

4条回答 默认 最新

  • 关注

    错误太多了,刚开始的指针赋值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; //修改
    };
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 12月9日
  • 已采纳回答 12月1日
  • 创建了问题 12月1日

悬赏问题

  • ¥50 有偿!centos curl port设置问题
  • ¥15 请问Quartus的Verilog代码怎么写?
  • ¥18 光催化第一性原理计算析氢效率STH怎么计算
  • ¥100 Mac 版foxmail 收邮件问题
  • ¥15 QWebEngineView
  • ¥15 如何使用shufflenet进行手写数字识别
  • ¥15 .net core 同时编辑怎么防止数据串了
  • ¥20 微信小程序播放直播流
  • ¥15 关于迷宫自走单片机循迹小车的知识
  • ¥15 python使用selenium工具爬取网站的问题