|
发表于 2020-5-4 18:53:31
|
显示全部楼层
根据你的想法我写了一个类似的:- #include<stdio.h>
- #include<stdlib.h>
- typedef int datatype;
- typedef struct node
- {
- datatype data;
- struct node* next;
- }listnode,*linklist;
- void headadd(linklist *L);
- void printflist(linklist L);
- int main()
- {
- int ch='y';
- linklist L=NULL;
- while(1)
- {
- printf("是否录入信息:");
- do
- {
- ch=getchar();
- }while(ch!='y'&&ch!='n');
- if(ch=='y')
- headadd(&L);
- else
- break;
- }
- printflist(L);
- return 0;
- }
- void headadd(linklist *L)
- {
- linklist s=(linklist)malloc(sizeof(listnode));
- linklist temp;
- if(s==NULL)
- {
- printf("申请空间失败!\n");
- exit(1);
- }
- printf("输入数据:\n");
- scanf("%d",&s->data);
- if(*L!=NULL)
- {
- temp=*L;
- *L=s;
- s->next=temp;
- }
- else
- {
- *L=s;
- s->next=NULL;
- }
- }
- void printflist(linklist L)
- {
- linklist s;
- s=L;
- while(s!=NULL)
- {
- printf("%d\t",s->data);
- s=s->next;
- }
- putchar('\n');
- }
复制代码
你的void headadd(linklist L)中只申请了一个动态内存,将数据循环放进去是不合理的,然后在这个函数传值时,要修改的时L这个指针的值(也就是下一个节点的地址),这个时候应该传入L的地址改为void headadd(linklist *L),对应的主函数中写为headadd(&L)。还有while (ch == 'y' || 'Y');
这里应改成while(ch=='y'||ch=='Y');在void printflist(linklist L)函数中改为linklist l = L;以及上面大佬说的
while (L->next != NULL)
{
printf("%d", l->data);
L = L->next; //少这一句
}
说的不对的地方,请多多指正 |
|