程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
int score;
char name[20];
struct student * next;
}Stu;
/** 创建链表 */
Stu* createLink(int arr[],char* name[],int len,int stat[]){
Stu *head=(Stu*)malloc(sizeof(Stu));
Stu *curStu=head;
for(int i=0;i<len;i++){
curStu->score=arr[i];
stat[arr[i]/10]++;
strcpy(curStu->name,name[i]);
if(i<len-1){
Stu *tmpStu=(Stu*)malloc(sizeof(Stu));
curStu->next=tmpStu;
}else{
curStu->next=NULL;
}
curStu=curStu->next;
}
return head;
}
/** 遍历链表 */
void display(Stu *head){
Stu *curStu=head;
while(curStu!=NULL){
printf("%s:%d\t",curStu->name,curStu->score);
curStu=curStu->next;
}
printf("\n");
}
/** 释放 */
void freeLink(Stu *stu){
if(stu!=NULL){
freeLink(stu->next);
free(stu);
}
}
/** 排序 */
Stu *sort(Stu *stu){
Stu *p=stu,*q=p->next,*r=q->next;
bool flag=false;
if(p->score<q->score){
p->next=r;
q->next=p;
stu=q;
p=stu,q=p->next,r=q->next;
}
while(r!=NULL){
if(q->score<r->score){
q->next=r->next;
r->next=q;
p->next=r;
flag=true;
}
p=p->next;
q=p->next;
r=q->next;
}
if(flag) {
return sort(stu);
}
return stu;
}
/** 查找 */
void find(char name[],Stu*h){
Stu *cur=h;
while(cur!=NULL&&strcmp(cur->name,name)!=0){
cur=cur->next;
}
if(cur!=NULL){
printf("found! %s:%d",cur->name,cur->score);
}else{
printf("not found!");
}
}
int main(){
int score_arr[]={99,83,54,84,63,76,44,81};
char* name_arr[]={"aa","bb","cc","dd","ee","ff","gg","hh"};
int stat[10];
memset(stat,0,sizeof(stat));
Stu *head=createLink(score_arr,name_arr,8,stat);
display(head);
for(int i=1;i<10;i++){
printf("%d~%d:%d\n",i*10,(i+1)*10,stat[i]);
}
printf("\nsorted,score:\t");
head=sort(head);
display(head);
find("eee",head);
freeLink(head);
return 0;
}