#define NULL 0
typedef struct food
{
char name[20];
int id;
int price;
int sum;
struct food *next;
}node,*list;
struct book
{
char name[20];
int price;
};
list creatlist(list l)
{
l = (list)malloc(sizeof(node));
if(!l)
{
printf("malloc fail\n");
}
memset(l->name,0,sizeof(20));
l->next = NULL;
l->id = 0;
l->price = 0;
l->sum = 0;
return l;
}
struct book ccc[3] = {{"qingjiaorousi",12},{"sijidourousi",11},{"yuxiangqiezi",15}};
char* serchname(int id)
{
char a[20] = {0};
strcpy(a,ccc[id].name);
return a;
}
int serchprice(int id)
{
int price;
price = ccc[id].price;
return price;
}
list addlist(list l, int id, int num)
{
list p,q,pbefore;
p = l;
printf("##%d ,p = %p\n",__LINE__,p);
while(p)
{
if(p->id != id)
{
printf("##%d\n",__LINE__);
pbefore = p;
p = p->next;
}
}
printf("##%d\n",__LINE__);
while(num)
{
printf("##%d,num = %d\n",__LINE__,num);
q = (list)malloc(sizeof(node));
q->id = id;
printf("q->id = %d\n",q->id);
strcpy(q->name,serchname(id));
printf("##%s\n",q->name);
q->price = serchprice(id);
printf("##%d\n",__LINE__);
l->sum += q->price;
printf("##%d,%p\n",__LINE__,p);
q->next = p;
printf("##%d,%p,q addr = %p\n",__LINE__,p,q);
pbefore->next = q;
p = q;
printf("##%d\n",__LINE__);
printf("##%d\n",__LINE__);
num--;
printf("##%d\n",__LINE__);
//free(q);
printf("-------------------%d\n",__LINE__);
}
p = l->next;
while(p)
{
printf("id foodname price\n");
printf("%d %s %d\n",p->id,p->name,p->price);
p = p->next;
}
return l;
}
void printfoodstatus(list l)
{
list p;
p = (list)malloc(sizeof(node));
p = l->next;
if(!p)
{
printf("food line is empty\n");
return -1;
}
while(p)
{
printf("id foodname price\n");
printf("%d %s %d\n",p->id,p->name,p->price);
p = p->next;
}
printf("total price is %d\n",l->sum);
}
list dellist(list l,int id,int num)
{
list p,pbefore,pnext;
int flag = 0;
int numtime;
p = l;
while(p)
{
if(p->id != id)
{
pbefore = p;
p = p->next;
}
else
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("the id don't exist\n");
return -1;
}
numtime = num;
while(num)
{
if(p->id != id)
{
printf("only have %d\n",numtime-num);
}
pbefore->next = p->next;
pnext = p->next;
free(p);
p = pnext;
num--;
}
}
int main()
{
list l;
int id;
int num;
int cmd;
while(1)
{
printf("please input your cmd\n");
printf("0:creat;1:add;2:del;3:print\n");
scanf("%d",&cmd);
switch(cmd)
{
case 0:
l = creatlist(l);
break;
case 1:
printf("input the id and num you want to add\n");
scanf("%d%d",&id,&num);
addlist(l,id,num);
break;
case 2:
printf("input the id and num you want to del\n");
scanf("%d%d",&id,&num);
dellist(l,id,num);
break;
case 3:
printfoodstatus(l);
break;
default:
printf("cmd err\n");
}
}
}