【发布时间】:2021-08-06 10:29:05
【问题描述】:
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node*next;
};
struct node*start;
void create(struct node*ptr)
{
char ch;
do
{
printf("Enter the data of node\n");
scanf("%d",&ptr->data);
fflush(stdin);
printf("Do you wish to continue?(y/n)\n");
ch=getchar();
if(ch=='y')
{
ptr=ptr->next;
}
else
ptr->next=NULL;
}while(ch=='y');
}
void insert(struct node*ptr)
{
struct node*p;
p=(struct node*)malloc(sizeof(struct node));
printf("Enter the value of data for node1\n");
scanf("%d",&p->data);
fflush(stdin);
p->next=ptr;
ptr=p;
}
void display(struct node*ptr)
{
printf("Your Linked list is\n");
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
int main()
{
printf("Hello and welcome to Linked List program\n");
start=(struct node*)malloc(sizeof(struct node));
create(start);
display(start);
printf("Let us now add a node to your linked list\n");
insert(start);
display(start);
return 0;
}
我的编译器正在跳过函数调用插入和显示。我已经检查了它们对我来说似乎正确的所有功能的逻辑。此外,在 printf 工作之前显示和创建。 print 语句后的函数(即插入和显示函数)不起作用。
【问题讨论】:
-
fflush()不应以stdin作为参数调用。所以首先要做的是重构代码,这样你就可以删除所有的fflush(stdin)调用。 -
使用调试器并单步调试代码。它会告诉你发生了什么。
-
malloc.h 已经过时了。请改用 stdlib.h。
标签: c linked-list dynamic-memory-allocation singly-linked-list function-definition