我正在尝试链接列表,但由于某种原因它没有做它应该做的事情。当我在选择 1 后输入数量时,一切都很好,直到将节点添加到现有列表中,之后数量变成一串奇怪的数字。而且,当我尝试将多个节点添加到捐赠列表时,程序就会崩溃。
编辑:上述问题已解决,但还有一个我忘记提及的问题是当我尝试打印列表时,没有打印任何内容。当我选择 4 时会发生这种情况。
EDIT2:打印功能只打印出第一个节点,之后什么也没有。请帮忙。
这是代码。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct donation{
char name[50];
int quant;
struct donation* next;
}donate;
donate* addItem(donate *mylist,donate *temp){
donate *front=(donate*)malloc(sizeof(donate*));
if(mylist==NULL)
return temp;
front=mylist;
while(mylist->next!=NULL)
mylist=mylist->next;
mylist->next=temp;
return front;
}
void print(donate* donList){
printf("Printing the Donations Table\n\n");
if(donList!=NULL){
while(donList->next!=NULL){
printf("%s %d\n",donList->name,donList->quant);
donList=donList->next;
}
}
}
main(){
donate *list=NULL;
while(1){
int choice;
printf("1. Add a donation\n);
printf("Enter your choice: ");
scanf("%d",&choice);
if(choice==1){
donate* temp=(donate*)malloc(sizeof(donate*));
printf("\nEnter inventory type: ");
scanf("%s",temp->name);
printf("Enter the amount: ");
scanf("%d",&temp->quant);
temp->next=NULL;
list=addItem(list,temp);
printf("\nDonation Added!\n");
printf("%s %d\n",list->name,list->quant);
}
else if(choice==4){
print(list);
}
}
system("pause");
return 0;
}
谢谢!