请教链表排序问题
程序代码:
# include <stdio.h> # include <malloc.h> # include <stdlib.h> //函数前置声明 struct Student * InputStudent(int); void OutputStudent(struct Student *); void paixu(struct Student *); //学生结构体 struct Student { int a; //年龄 char b[10]; //姓名 struct Student * pNext; //指针域 }; //主函数 int main(void) { int len; printf("请输入学生的人数:"); scanf("%d", &len); struct Student * p; p = InputStudent(len); printf("\n\n"); paixu(p); OutputStudent(p); return 0; } //输入函数 struct Student * InputStudent(int len) { int i; //构建头结点 struct Student * p = (struct Student *)malloc(sizeof(struct Student)); if( NULL == p) { printf("构建失败!"); exit(-1); } //构建链表 struct Student * t = p; t->pNext = NULL; for(i=0; i<len; i++) { struct Student * pNEW = (struct Student *)malloc(sizeof(struct Student)); if( NULL == pNEW) { printf("构建失败!"); exit(-1); } printf("请输入第 %d 个学生的信息:\n", i+1); printf("年龄:"); scanf("%d", &pNEW->a); printf("姓名:"); scanf("%s", pNEW->b); t->pNext = pNEW; pNEW->pNext = NULL; t = pNEW; } return p; } //输出函数 void OutputStudent(struct Student * p) { int i = 1; p = p->pNext; while( NULL != p) { printf("第 %d 个学生的信息:\n", i); printf("年龄:%d", p->a); printf("姓名:%s\n", p->b); p = p->pNext; i++; } return; } //排序函数 void paixu(struct Student * p) { struct Student * t; struct Student * t1; struct Student * t2; struct Student tt; int z = 0; int i, j; p = p->pNext;//取首节点 t = t2 = p; //取链表数 while( NULL != t) { z++; t = t->pNext; } t = p->pNext;//取第二节点 //开始循环比较 for(i=0; i<z; i++) { for(j=0; j<z-i; j++) { if( (p->a) < (t->a) ) { tt = *p; *p = *t; *t = tt; t1 = p->pNext; p->pNext = t->pNext; t->pNext = t1; } //进入下一个节点 p = p->pNext; t = t->pNext; //获取首节点地址进入第二次的i循环 if( NULL == t) { p = t2; t = p->pNext; } } } return; }
终于排障并完成了排序了。。。。
[ 本帖最后由 lixnkei 于 2010-3-8 16:16 编辑 ]