|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iostream.h>
#include<string>
#include<malloc.h>
#define LEN sizeof(struct student)
int n; /********用于记录总共有多少个数据即链表*************/
struct student
{
long num;
float score;
struct student *next;
};
struct student *great(); /*******创建链表******/
struct student *insert(struct student *head,struct student *p0); /********插入一个链表,使不同学号学生的 score从小到大排列*********/
struct student *del(struct student *head , int num); //*********删除链表**********/
void print( struct student *head); /*******打印链表******/
struct student *cfinsert(struct student *head); /*****实现多次插入数据并排列好***********/
struct student *great()
{
struct student *head,*p1,*p2;
head=0; /**********注意置零*****/
p1=p2=(struct student *)malloc(LEN);
cout<<"please enter the student num " ;
cin>>p1->num;
cout<<"please enter the student score " ;
cin>>p1->score;
while(p1->num)
{
n++;
if(n==1)
{
head=p1;
}
else
{
/*******需要补全p2->next,因为是创建过程所以需要把每一个链表的元素都补全否则head不能够找到地址*************/
p2->next=p1;
p2=p2->next;
/*********************************************/
}
p1=p1->next;
p1=(struct student *)malloc(LEN);
cout<<"please enter the student num " ;
cin>>p1->num;
cout<<"please enter the student score " ;
cin>>p1->score;
}
p2->next=NULL;
return head;
}
struct student *del(struct student *head , int num)
{
struct student *p1, *p2;
p1=p2=head;
if(head==NULL)
{
return head;
}
else
{
while(p1!=NULL && p1->num!=num )
{
/******注意下面两行与上面的创建链表不一样,它不需要保存p2->next,因为这个链表******/
p2=p1;
p1=p1->next;
/******本身是完整的,只需要找到要删除的那个地址,再根据条件进行后续操作*****/
}
if(p1->num==num)
{
if(head==p1) /**********注意要分开考虑第一个链表为要删除的数据的情况*****/
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
}
else
{
cout<<"没有要删除的数据"<<endl;
}
return head;
}
}
struct student *insert(struct student *head,struct student *p0) /******插入数据****/
{
struct student *p1, *p2;
p1=head;
if(head==NULL)
{
head=p0;
}
else
{
while(p0->score>p1->score && p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p0->score<=p1->score)
{
if(head==p1)
{
head=p0;
p0->next=p1;
}
else
{
p2->next=p0;
p0->next=p1;
}
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
return head;
}
struct student *cfinsert(struct student *head) /*****实现插入数据****/
{
struct student stu;
cout<<"请输入要插入的学生学号及分数: " ;
cout<<"the num is: ";
cin>>stu.num;
cout<<"the score is: ";
cin>>stu.score;
while(stu.num!=0)
{
head=insert( head, &stu);
cout<<"the num is: ";
cin>>stu.num;
cout<<"the score is: ";
cin>>stu.score;
}
return head;
}
void print( struct student *head)
{
cout<<"********************************"<<endl;
cout<<"总共有"<<n<<"的同学的数据"<<endl;
while(head)
{
cout<<"学号为"<<head->num<<"的学生分数是"<<head->score<<endl;
head=head->next;
}
}
void main()
{
struct student *head;
struct student *p1,*p2;
int x;
p1=great();
print(p1);
cout<<"输入要删除的学号 ";
cin>>x;
n--;
head=del(p1,x);
print(head);
p2=cfinsert(head);
print(p2);
}
file:///C:/Users/acer/AppData/Roaming/Tencent/Users/1147745939/QQ/WinTemp/RichOle/I8~]B0U@NQBUBLVX4CH4$IC.png
图片是运行的结果,知道哪里错的同志回复一下,最好加我QQ1147745939 谢谢 |
-
运行结果
|