DraHong 2021-09-16 23:05 采纳率: 100%
浏览 41
已结题

C语言基础.关于链表

尾插法建立的链表长度是输入个数的两倍。
自己找的问题是:在有数据的节点后有一个空节点,然后才是下一个带数据的节点。
自己寻找过,也和同学讨论过,都感觉没啥大问题,就是找不出来,怎么改进一下,希望大佬解答,下面是代码

感谢大佬

#include<stdio.h>#include<stdlib.h> #define LEN sizeof(struct Deat)struct Deat{ char deat; //数据域 struct Deat *next; //指针域 };struct Deat Creat(){ struct Deat head,p,q; //头指针head,两个指针,一个开辟新空间,另一个来指向开辟的新空间 char c; //用来存放输入的数据进行判断 p=(struct Deat)malloc(LEN); head=p; head->next=NULL; printf("请输入链表数据,以$结束!\n"); while((c=getchar())!='$'){ p->deat=c; q=(struct Deat)malloc(LEN); p->next=q; p=q; p->next=NULL; } return head;}void Show(struct Deatl) { while(l->next!=NULL){ putchar(l->deat); l=l->next; }}int Howlong(struct Deatl){ int a=0; while(l->next!=NULL){ a=a+1; l=l->next; } return a;}int main(){ struct Deat *l; l=Creat(); printf("----------------------------\n"); Show(l); printf("----------------------------\n"); printf("该链表长度为%d\n",Howlong(l)); return 0;}



  • 写回答

2条回答 默认 最新

  • qzjhjxj 2021-09-17 09:53
    关注

    在链表创建环节,getchar() 多读入了缓冲区剩余空格符,所以多创建了一个结点,修改如下,供参考:

    #include<stdio.h>
    #include<stdlib.h> 
    #define LEN  sizeof(struct Deat)
    
    struct Deat{ 
        char deat; //数据域 
        struct Deat *next; //指针域 
    };
    struct Deat *Creat()
    { 
        struct Deat *head, *p, *q; //头指针head,两个指针,一个开辟新空间,另一个来指向开辟的新空间 
        char c; //用来存放输入的数据进行判断 
        head=(struct Deat*)malloc(LEN); 
        head->next=NULL; 
        p = head;
        printf("请输入链表数据,以$结束!\n"); 
        while((c=getchar())!='$')
        { 
            getchar();             //吸收缓冲区多余空格符
            q=(struct Deat*)malloc(LEN); 
            q->next = NULL;
            q->deat=c; 
            
            p->next=q; 
            p=q; 
            //p->next=NULL; 
        } 
        return head;
    }
    void Show(struct Deat* l) 
    { 
        while(l->next!=NULL)
        { 
            l=l->next;
            putchar(l->deat); 
        }
        printf("\n");
    }
    int Howlong(struct Deat* l)
    { 
        int a = 0;;
        while(l->next!=NULL)
        { 
            l=l->next; 
            a=a+1;
        } 
        return a;
    }
    int main()
    { 
        struct Deat *l; 
        l=Creat(); 
        printf("----------------------------\n"); 
        Show(l); 
        printf("----------------------------\n"); 
        printf("该链表长度为%d\n",Howlong(l)); 
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月25日
  • 已采纳回答 9月17日
  • 创建了问题 9月16日

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?