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

GPU小码农 2013-03-28 11:39:35
#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;
}
...全文
124 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Carl_CCC 2013-03-28
  • 打赏
  • 举报
回复
跑了下,代码没问题,应该是楼主测试的时候输入有问题。楼主可以吧测试过程贴出来。

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧