shuo.J 2021-03-20 16:07 采纳率: 50%
浏览 40
已采纳

C语言程序写出来了,关于循环单链表,不知道哪里出错了跑不出来,麻烦大神帮忙看看,谢谢!

将数据元素b插入循环单链表Head中第一个元素为a的结点之前。

#include<stdio.h>
#include<malloc.h>
#define LNode sizeof(struct num)
struct num
{
    char n;
    struct num*next;
};
struct num*creat(void)                                 //创造链表函数 
{
    struct num*head,*r,*s;
    char n;
    head=(struct num*)malloc(sizeof(struct num));
    r=head;
    scanf("%c",&n);
    while(n!=0)
    {
        s=(struct num*)malloc(sizeof(struct num));
        s->n=n;
        r->next=s;
        r=s;
        scanf("%c",&n);
    }
    r->next=head;
    return head;
}
struct num*print(struct num*head)                      //输出链表函数 
{
    struct num*p;
    p=head->next;
    while(p)
    {
        printf("%5c",p->n);
        p=p->next;
    }
    printf("\n");
}
struct num*insert(struct num*head)   
{
    struct num*p,*q,*save;
    if(head->next==head)
    {
        q=(struct num*)malloc(sizeof(struct num));
        q->n='b';
        head->next=q;
        q->next=head;
    }
    else
    {
        p=head->next;
        head->n='a';
    }
    while(p->n!='a')
    {
        save=p;
        p=p->next;
    }
    q=(struct num*)malloc(sizeof(struct num));
    q->n='b';
    q->next=p;
    save->next=q;
    return head;
}
int main(void)
{
    struct num*head,*p2;
    head=creat();
    print(head);
    insert(head);
    print(head);
    return 0;
}
 

  • 写回答

1条回答 默认 最新

  • 幻灰龙 2021-03-20 16:28
    关注

    insert 里面,变量 `struct num*p` 在语句 ` while(p->n!='a')` 之前,如果分支进入` if(head->next==head)` 的情况,指针 p 并没有被初始化,此处就有问题。建议先对你的 `insert`  画一下程序的流程图,先把流畅梳理清楚。

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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)