Created
October 13, 2016 07:27
-
-
Save sfantree/8c05dd4aabd151b181a2bdb1f6802438 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
using namespace std; | |
typedef struct Lnode{ | |
char name[20]; | |
float num; | |
struct Lnode *next; | |
}Lnode,*Linklist; | |
void CreateList(Linklist &L,int n)//尾插法,p38页 | |
{ | |
Linklist r,p; | |
int i; | |
L=new Lnode; | |
L->next=NULL; | |
r=L; | |
for(i=0;i<n;i++) | |
{ | |
p=new Lnode; | |
cout<<"请输入名字:"; | |
cin>>p->name; | |
cout<<"请输入分数:"; | |
cin>>p->num; | |
p->next=NULL; | |
r->next=p; | |
r=p; | |
} | |
} | |
void DisplayList(Linklist &L)//验证列表创建是否成功,在上次实验基础上修改 | |
{ | |
Linklist p; | |
p=L->next; | |
while(p!=NULL) | |
{ | |
cout<<p->name<<" "<<p->num<<endl;; | |
p=p->next; | |
} | |
} | |
void Insert(Linklist &L,int i)//在第i个位置前插入元素 ,p34页 | |
{ | |
Linklist p,s; | |
p=L; | |
int j=0; | |
while(p && (j<i-1)) | |
{p=p->next;++j; | |
} | |
s=new Lnode; | |
cout<<"请输入名字:"; | |
cin>>s->name; | |
cout<<"请输入分数:"; | |
cin>>s->num; | |
s->next=p->next; | |
p->next=s; | |
} | |
void Delete(Linklist &L,int i)//删除第i个位置的元素,p35页 | |
{ | |
Linklist p,q; | |
p=L; | |
int j=0; | |
while((p->next)&&(j<i-1)) | |
{ | |
p=p->next; | |
++j; | |
} | |
q=p->next; | |
p->next=q->next; | |
delete q; | |
} | |
void Average(Linklist &L) | |
{ | |
float average,sum=0; | |
Linklist p; | |
int i=0; | |
p=L->next; | |
while(p!=NULL) | |
{ | |
sum=sum+p->num; | |
p=p->next; | |
i++; | |
} | |
average=sum/i; | |
cout<<average<<endl; | |
} | |
int main() | |
{ | |
int n,c=0,a=0,b=0;//a代表要插入的位置,b代表要删除的位置 ,c代表选择 | |
Linklist L; | |
cout<<"请输入学生人数:"; | |
cin>>n; | |
CreateList(L,n); | |
//DisplayList(L); | |
//Insert(L,1); | |
//DisplayList(L); | |
// Delete(L,2); | |
// DisplayList(L); | |
// Average(L); | |
while(1) | |
{ | |
cout<<"输入你要的操作: 1 插入 2 删除 3 显示 4 平均成绩 5退出 "<<endl; | |
cin>>c; | |
switch(c) | |
{case 1: | |
cout<<"要插入的位置:"; | |
cin>>a; | |
Insert(L,a); | |
break; | |
case 2: | |
cout<<"要删除的位置:"; | |
cin>>b; | |
Delete(L,b); | |
break; | |
case 3: | |
DisplayList(L); | |
break; | |
case 4: | |
Average(L); | |
break; | |
case 5: | |
exit(0); | |
break; | |
default: | |
break; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment