下面贴一下我改的几个地方#include<stdio.h>
#include<stdlib.h>
struct Student
{
char name[20];
int age;
float score;
char num[20];
};
struct Node
{
struct Student data;
struct Node *next;
};
struct Node *CreatLink(void);
void InitLink(struct Node *head);
void QuickSort(struct Node *head, struct Node *tail);
void OutputLink(struct Node *head);
int main(void)
{
struct Node *head = CreatLink();
InitLink(head);
QuickSort(head, NULL);
printf("排序后的结果如下:\n");
OutputLink(head);
return 0;
}
struct Node *CreatLink(void)
{
struct Node *head = (Node *)malloc(sizeof(Node));//这里报错了 申请内存应该这样吧
int i = 0;
int cnt = 0;
struct Node *move = head;
move->next = NULL;
printf("请输入学生的数量:");
scanf("%d", &cnt);
getchar();
for (i = 1; i <= cnt; i++)
{
struct Node *fresh = (Node *)malloc(sizeof(Node));//同上
move->next = fresh;
fresh->next = NULL;
move = fresh;
}
return head;
}
void InitLink(struct Node *head)
{
int i = 1;
struct Node *move = head->next;
while (move != NULL)
{
printf("请输入第%d个学生的名字:", i);
scanf("%s", move->data.name);
getchar();
printf("请输入第%d个学生的年龄:", i);
scanf("%d", &(move->data.age));
getchar();
printf("请输入第%d个学生的分数:", i);
scanf("%f", &(move->data.score));
getchar();
printf("请输入第%d个学生的学号:", i);
scanf("%s", move->data.num);
getchar();
move = move->next;
i++;
}
return;
}
void QuickSort(struct Node *head, struct Node *tail)
{
struct Node *key;
struct Node *move;
struct Node *save = NULL;
if (head->next == tail || head->next->next == tail)
{
return;
}
key = head->next;
move = head->next;
while (move && move->next != tail) //排序这里要考虑 move不能为NULL的情况 否则它就没有->next
{
if ((move->next->data.score) > (key->data.score))
{
save = move->next;
move->next = move->next->next;
save->next = head->next;
head->next = save;
}
move = move->next;
}
QuickSort(head, key);
QuickSort(key, tail);
}
void OutputLink(struct Node *head)
{
struct Node *move = head->next;
int i = 1;
while (move != NULL)
{
printf("第%d位学生信息为\n", i);
printf("姓名:%s; 年龄:%d; 分数:%.2f; 学号:%s\n", move->data.name, move->data.age, move->data.score, move->data.num);
i++;
move = move->next;
}
return;
}
|