c0re 2022-03-28 18:35 采纳率: 75%
浏览 39
已结题

c语言,链表节点插入

求解释一下我的代码为什么部分错误在PTA上。谢谢亲们,实在是检查不出来哪里错误!我想知道我的代码哪里错了!

 #include <stdio.h>
 #include <stdlib.h>
    struct node
  {
      int data;
      struct node *next;
  };
    struct node *creat(void);//这个是可能出错的函数
    struct node *creat(void)
    {
        int i,m,n,ii;
        struct node *h,*t,*p,*t2;
        h=(struct node *)malloc(sizeof(struct node));
        h->next=NULL;

        t=h;
        t2=h;
        //对应两种情况
        scanf("%d",&n);
        for (i=0;i<n;i++)
        {
            scanf("%d",&m);
            p=(struct node *)malloc(sizeof(struct node));
            scanf("%d",&p->data);
            p->next=NULL;
        if(m>i)//如果输入的数大于链表中的元素个数放在最后面
        {
            t=h;
            while(t->next!=NULL)
            {
                t=t->next;
            }
            t->next=p;
            p->next=NULL;
        }

          else//不大于的情况插在m元素后面
          {
              t2=h;
                for(ii=0;ii<m;ii++)
                {
                    t2=t2->next;
                }
              p->next=t2->next;
              t2->next=NULL;
              t2->next=p;
            }
        }
        return h;

    }
    //这个不可能出错下面是打印链表
        void print(struct node *head);
        void print(struct node *head)
        {
                struct node *p;
                int m=0;
                p=head->next;
                while(p)
                {
                    m++;
                    if(m==1)
                        printf("%d",p->data);
                    else
                    {
                          printf(" %d",p->data);

                    }
                    p=p->next;
                }
            printf("\n");

        }
        //下面是主函数也不可能出错
int main (void)
    {
        struct node *h;
        h=creat();
        print(h);
        return 0;
    }

img

  • 写回答

1条回答 默认 最新

  • zp_diandiandidi 2022-03-29 08:31
    关注

    代码太多了,建议你学会 debug,可以很快的帮你定位问题,学习 debug 很快的,百度下一会就明白了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月15日
  • 已采纳回答 5月7日
  • 创建了问题 3月28日

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件