回 帖 发 新 帖 刷新版面

主题:[讨论]关于单链表的插入,看看有什么问题,结果不对.紧急求助

百货公司仓库中有一批电视机,按其价格从低到高的次序构成了一个单链表并存与计算机中,链表的每个结点指出同样价格的若干台。现在又新到m台价格为h元的电视机入库。试编写出仓库电视机链表增加电视机的算法。用C实现.

#include <stdio.h>
#include <malloc.h>


typedef struct node     /*定义结点类型,price价格,number数量,next链接指针*/
{int price;
 int number;
 struct node *next;}jd;

jd *zj(jd *q,int x,int y)  /*增加结点的函数*/
  {jd *p,*s,*k;
   p=q;
   s=q;
   while(p->price<x)
     p=p->next;
   if(p->price==x)
     p->number=p->number+y;
   if(p->price>x)
     {while(s->next!=p)
       s=s->next;
      k=(jd*)malloc(sizeof(jd));
      k->price=x;
      k->number=y;
      k->next=s->next;
      s->next=k;}
   return q;}               /*返回处理后的头指针*/



main()
{int m,h,b,d;
 jd *l,*t,*head;
 head=NULL;
 l=head;

 printf("please imput the tv price and number bank you want to add to,and input 00 to the end\n");
 scanf("%d%d",&b,&d);                 
 while(b!=0&&d!=0)
 {t=(jd*)malloc(sizeof(jd));/*先建立一个要处理的单链表,存入价格,数量,以00结束
   t->price=b;                         
   t->number=d;
   t->next=NULL;
   if(head==NULL)
     {head=t;
      l=t;}
   else{l->next=t;
        l=t;}
   scanf("%d%d",&b,&d);}
 printf("please imput the tv price and number you want to add\n");
 scanf("%d%d",&h,&m);                        /*输入要增加的电视价格和数量*/
 t=head;
 while(t->next!=NULL)
   printf("%d %d",t->price,t->number); /*输出未经处理的格格和数量表(便于比较)
 head=zj(head,h,m);
 t=head;
 while(t->next!=NULL)
   printf("%d %d",t->price,t->number);  /*输出经处理的价格和数量表.

}

运行后似乎是死循环,还没等输入就一版的00,不停地滚.看不出有什么问题啊.
 

回复列表 (共3个回复)

沙发

b d 没有初始化,编译器的默认值为0。改一下你的while的循环条件看看!?

板凳

麻烦,我还想问一下,head指针和head结点到底有什么不同啊,我每次定义总会出错,他们两个里边哪一个可以存数据啊,谢谢啦

3 楼


main()里面最好有返回值 例如:return 0;

我来回复

您尚未登录,请登录后再回复。点此登录或注册