首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

新手问:链表有关问题,建立删除输出都正确,插入功能不正确,求改正!多谢

2013-04-02 
新手问:链表问题,建立删除输出都正确,插入功能不正确,求改正!谢谢!#includestdio.h#includemalloc.h#d

新手问:链表问题,建立删除输出都正确,插入功能不正确,求改正!谢谢!
#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct stu)
#define st struct 
st stu
{
long num;
float score;
st stu *next;
};
int n;
//建立
st stu * creat(void)
{
st stu *head,*p1,*p2;
n=0;head=NULL;
p1=p2=(st stu *)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
while(p1->num!=0)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(st stu*)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
p2->next=NULL;
return(head);
}//建立完毕
void print(st stu * head)
{
st stu*p;
printf("\nOK!看下面的输出吧:\n");
p=head;
if(head!=NULL)
  do
  {
  printf("%ld\t%5.1f\n",p->num,p->score);
  p=p->next;
  }while(p!=NULL);
}
//删除函数
st stu *del(st stu *head,long num)
{
 st stu *p1,*p2;p1=head;
 if(head==NULL)
 {
 printf("\nlist null!");
 return head;
 }
 while(num!=p1->num && p1->next!=NULL)
 {
   p2=p1;
   p1=p1->next;
 }
 if(num==p1->num)
 {
   if(p1==head)head=p1->next;
   else p2->next=p1->next;
   printf("delete:%ld\n",num);
   n=n-1;
 }
else printf("%ld not have have been found!\n",num);
return head;
}//删除完毕

//插入节点的函数
st stu * insert(st stu* head,st stu * stud)
{
  st stu *p0,*p1,*p2;
  p1=head;
  p0=stud;
  if(head==NULL)
  {
  head=p0;p0->next=NULL;
  }
  else 
  {
     //要对插入的位置进行讨论
  while(  (  p0->num  >  p1->num )  &&  ( p1->next != NULL   ) )
  {
  p2=p1;
  p1=p1->next;//移动,寻找
  }

      if( p0->num <= p1->num  )
  {
    if(head==p1)
{
     head=p0;
}
else 
{
 p2->next=p0;
}
        p0->next=p1;
  }
  else//最后一个情况
  {
  p1->next=p0;p0->next=NULL;
  }
  }//讨论完毕!
  n=n+1;
  return head;
}
int main(void)
{

st stu * get,*u;
long x;
get=creat();
print(get);
printf("请输入要删除的节点:\n");
scanf("%ld",&x);
get=del(get,x);
print(get);
printf("请输入要插入的节点:");
u=(st stu *)malloc(LEN);
scanf("%ld,%f",&u->num,&u->score);
get=insert(get,u);
print(get);
return 0;
} struct insert null delete
[解决办法]
跑了下,代码没问题,应该是楼主测试的时候输入有问题。楼主可以吧测试过程贴出来。

热点排行