有一串打乱的成绩,现要求你们将他们从低到高排列

tech2023-02-14  117

输入 每一行为姓名和成绩

以#作为输入结束标志

输出 输出排序后的结果

样例输入 LI 95 ZHAO 80 SUN 85 JIN 60 QIAN 70 WANG 90 ZHAN 85

样例输出 JIN 60 QIAN 70 ZHAO 80 SUN 85 ZHAN 85 WANG 90 LI 95 提示 链表操作

#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node{ char name[1000]; int score; node *next; }Node; /*链表创建*/ Node *Creat() { Node *head,*tail,*p; char x[1000]; int y; head=(Node *)malloc(sizeof(Node)); tail=head; scanf("%s%d",x,&y); while(strcmp(x,"#")!=0) { scanf("%d",&y); p=(Node *)malloc(sizeof(Node)); if(p==NULL) return NULL; strcpy(p->name,x); p->score=y; p->next=NULL; tail->next=p; tail=p; scanf("%s",x); } return head; } /*链表排序*/ void Sort(Node *head) { Node *pp,*p,*q,*last; last=head; while(last->next!=NULL) { last=last->next; } while(last!=head->next) { pp=head; p=pp->next; while(p!=last) { q=p->next; if(p->score>q->score) //依据score值进行排序 { pp->next=q; p->next=q->next; q->next=p; if(last==q) last=p; } pp=(p->score<=q->score)?p:q; p=pp->next; } last=pp; } } /*链表遍历*/ void Traverse(Node *head) { for(head=head->next;head;head=head->next) printf("%s %d\n",head->name,head->score); } int main() { Node *a; a=Creat(); Sort(a); Traverse(a); }

运行结果如下: 这道题的思路非常简单和明显,但是我在做的时候却老是卡在一些非常小的问题上: (1)结构体中含有字符数组,在链表创建中的元素加入时,不能采用直接赋值的形式,而是应当使用strcpy函数 (2)在需要排序的序列中有值相同时,应当在排序函数中注意某些部分是否将相等的情况包含进去,例如这次的数据样例中就有值相同的元素(没有注意到这点,浪费了很多时间) (3)链表冒泡排序中的If(last==q)的情况十分必要

最新回复(0)