使用链接列表时出错。
我发现即使我越来越多地创建节点。
但实际上,每次输入新的integer
时,所有这些都存储在同一节点中。我们可以在打印它们时看到它,即使我写"\n"
,程序也不会进入下一行。谢谢你的帮助!
#include <stdio.h>
#include <stdlib.h>
///This is some codes for me to practice linkedlist.
///3 functions here. "int main" for input the integer for every node; print_linkedlist for printing the integer stored in every
///node; and the searchment for searching the integer to determine whether it's included in the whole linkedlist
///Thank you!
typedef struct dish
{
int num;
struct dish *next;
}node;
void print_linkedlist(void);
void searchment(void);
int main()
{
FILE *fp;
fp=fopen("notebook.txt","w");
node *head,*n1,*n2;
head=(node *)malloc(sizeof(node));
head->next=(node *)malloc(sizeof(node));
n1=head->next;
n1->next=NULL;
while(1)
{
printf("*\n");
fflush(stdin);
scanf("%d",&n1->num);
fprintf(fp,"%d",n1->num);
if(n1->num==0)
break;
n1->next=(node *)malloc(sizeof(node));
n2=n1->next;
n1=n2;
n1->next=NULL;
}
fclose(fp);
print_linkedlist();
///searchment();
return 0;
}
void print_linkedlist(void)
{
FILE *fp;
fp=fopen("notebook.txt","r");
node *head,*n1,*n2;
head=(node *)malloc(sizeof(node));
head->next=(node *)malloc(sizeof(node));
n1=head->next;
while(1)
{
fscanf(fp,"%d\n",&n1->num);
if(n1->next==NULL)
break;
printf("%d\n",n1->num);
n2=(node *)malloc(sizeof(node));
n1=n2;
n1->next=NULL;
n1->next=(node*)malloc(sizeof(node));
}
fclose(fp);
}
void searchment(void)
{
FILE *fp;
fp=fopen("notebook.txt","r");
printf("input what you want to search\n");
int w;
fflush(stdin);
scanf("%d",&w);
node *head,*n1,*n2;
head=(node *)malloc(sizeof(node));
head->next=(node *)malloc(sizeof(node));
n1=head->next;
while(1)
{
fflush(stdin);
fscanf(fp,"%d",&n1->num);
printf("%d\n",n1->num);
if(n1->num==w)
{
printf("%d",n1->num);
break;
}
else if(n1->next==NULL)
{
printf("sorry, there is not\n");
break;
}
else
{
n1->next=(node *)malloc(sizeof(node));
n2=n1->next;
n1=n2;
n1->next=NULL;
}
}
fclose(fp);
}