为强化通用性,在强制类型转换上费了点功夫,另测试了下链表头插、中间插的插入功能,做了些许修改。先随便写了个交换数据方式的选择排序法的链表排序,并用同一个排序函数演示了“按学号顺序排序、按C语言成绩倒序排序、按平均成绩倒序排序”,演示结果正确。
链表排序函数:struct student *lsort(struct student *head,int offset,int vartype,int sortflg)
参数说明:
表头指针 head
排序变量偏移量 offset
排序变量类型 vartype(0:char、1:int、2:float、3:double、4、string暂时忽略)
排序方式 sortflg(0:增序、1:降序)
代码如下:
链表排序函数:struct student *lsort(struct student *head,int offset,int vartype,int sortflg)
参数说明:
表头指针 head
排序变量偏移量 offset
排序变量类型 vartype(0:char、1:int、2:float、3:double、4、string暂时忽略)
排序方式 sortflg(0:增序、1:降序)
代码如下:
程序代码:
#include <stdio.h> #include <stdlib.h> #include <time.h> struct student { int num; float c; float vb; float java; float ave; struct student *next; }; struct student *insert(struct student *head,struct student num,int pos) {//在指定位置插入一个数据为num的节点,pos=0头插,-1尾插 int i=0; struct student *p,*pre,*ph; p=(struct student*)malloc(sizeof(struct student)); if (p==NULL)return p; *p=num; pre=NULL; ph=head; while(pos&&pos!=++i&&ph) { pre=ph; ph=ph->next ; } if(pre==NULL) { p->next=head; head=p; } else { pre->next=p; p->next=ph; } return head; } void listsco(struct student *head) {//显示链表成绩 printf("学号 C语言 VB语言 JAVA 平均分\n"); while(head!=NULL) { printf("%-8d%-8.2f%-8.2f%-8.2f%-8.2f\n",head->num ,head->c ,head->vb ,head->java ,head->ave ); head=head->next ; } } struct student *lsort(struct student *head,int offset,int vartype,int sortflg) { /*交换数据方式链表排序参数说明: 表头指针 head 排序变量偏移量 offset 排序变量类型 vartype(0:char、1:int、2:float、3:double、4、string暂时忽略) 排序方式 sortflg(0:增序、1:降序)*/ struct student *pi,*pj,*p,num; unsigned long i,j,k; pi=head; while(pi->next) { p=pi; pj=pi->next; while(pj) { i=(unsigned long)p+offset; j=(unsigned long)pj+offset; if(vartype==0)k=(int)(*(char*)i>*(char*)j)^sortflg; if(vartype==1)k=(int)(*(int*)i>*(int*)j)^sortflg; if(vartype==2)k=(int)(*(float*)i>*(float*)j)^sortflg; if(vartype==3)k=(int)(*(double*)i>*(double*)j)^sortflg; if(k)p=pj; pj=pj->next; } if(p!=pi) { num=*p; *p=*pi; *pi=num; pj=p->next; p->next=pi->next; pi->next=pj; } pi=pi->next; } return head; } void main() { struct student *head=NULL,*p,num; int i; srand(time(0)); for(i=0;i<8;i++) { num.num=i+1; num.c =(rand()%800)/10.0+20; num.vb =(rand()%800)/10.0+20; num.java =(rand()%800)/10.0+20; num.ave =(num.c+num.vb+num.java)/3; num.next =NULL; head=insert(head,num,-1); } num.num=18; head=insert(head,num,3); //测试中间插入节点 num.num=38; head=insert(head,num,0); //测试头插 listsco(head); head=lsort(head,(int)(&head->num)-(int)head,1,0); printf("按学号顺序排序\n"); listsco(head); head=lsort(head,(int)(&head->c)-(int)head,2,1); printf("按C语言成绩倒序排序\n"); listsco(head); head=lsort(head,(int)(&head->ave)-(int)head,2,1); printf("按平均成绩倒序排序\n"); listsco(head); while(head) {//释放申请的空间要成为习惯 p=head; head=head->next; free(p); } system("pause"); }