http://www.oschina.net/code/snippet_252667_27314#comments
这个代码有很多错误,估计是从老谭书上抄来但是很多还抄错了:对照老谭的书好好研究下。切记!
p2是p1的跟屁虫!切记
#include"stdio.h"
#include"malloc.h"
struct stu
{
int num;//这个是学号
float score;//这个是分数
struct stu *next;
};
struct stu*create()
{
int n;//这个n这里不大合适 ,最好弄个全局的
struct stu *head,*p1,*p2;
p1=p2=(struct stu*)malloc(sizeof(struct stu));
scanf("%d %f",&p1->num,&p1->score);
head=NULL;
n=0;
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else
{
p2->next=p1;
p2=p1;
p1=(struct stu*)malloc(sizeof(struct stu));
scanf("%d %f",&p1->num,&p1->score);
}
}
p2->next=NULL;
return head;
};
//难点在插入操作的实现上(默认从小到大排列的)
struct stu *insert(struct stu *head,struct stu *stud)
{
struct stu *p0,*p1,*p2;
p1=head;
p0=stud;
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;
}
//这个地方要怎么维护总的num呢 ?
return head;
};
//删除操作难度次之
struct stu *del(struct stu *head,int num)
{
struct stu *p1,*p2;
p1=head;
if(head!=NULL)
{
while((p1->num<num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)//找到节点了
{ //这里要考虑删除头节点的情况
p2->next=p1->next;
p2=p1;
//要考虑删除的节点内存释放
//要考虑维护n的数目
}
else//没有找到节点
{
printf("NO Result!!!\n");
}
}
else
printf("The linklist is EMPTY\n");
return head;
};
void print(struct stu *head)
{
struct stu *p;
p=head;
while(p)
{
printf("%d %f\n",p->num,p->score);
p=p->next;
}
}
void main()
{
int n;
struct stu *create();
struct stu *insert(struct stu *head,struct stu *stud);
void print(struct stu *head);
struct stu *head,*p,*p1;
head=create();
p=head;
print(p);
printf("please input :\n");
scanf("%d %f",&p1->num,&p1->score);
p=insert(head,p1);
print(p);
printf("please input the del num:\n");
scanf("%d",&n);
p=del(head,n);
print(p);
}
浙公网安备 33010602011771号