current position:Home>Dynamic linked list failed to use bubble sorting

Dynamic linked list failed to use bubble sorting

2022-02-02 22:48:14 CSDN Q & A

Create dynamic linked list , Enter the corresponding score and sort according to the score , But when you enter more than two sets of data, the program crashes , Ask for an answer

#include"stdio.h"#include"string.h"#include"stdlib.h"struct student{    int id;    char name[20];    float score;    struct student *next;};void order(struct student a[10]);int i,n,j;float m;int main(){    struct student *p1,*p2,*head;    struct student a[10];    printf(" Enter the number of players :\n");    scanf("%d",&n);getchar();    printf(" Enter the name of each player id Number 、 Name and score :\n");    p1=p2=(struct student*)malloc(sizeof(struct student));    for(i=0;i<n;i++)    {        printf("Input id and name:\n");        scanf("%d %s",&p2->id,&p2->name);        printf("Input 5 scores:\n");        p2->score=0;        for(j=0;j<5;j++)        {            scanf("%f",&m);            p2->score+=m/5.0;        }        if(i==0){
   
   
   
   head=p2;head->next=NULL;}        else         {            head->next=p2;            p2=p2->next;        }        p2=(struct student*)malloc(sizeof(struct student));    }    p2->next=NULL;    for(i=0;i<n;i++)    {        a[i].id=p1->id;        strcpy(a[i].name,p1->name);        a[i].score=p1->score;        p1=p1->next;    }    order(a);    printf(" Ranking and average score per person :\n");    for(i=0;i<n;i++)        printf("%d %s %.2f\n",a[i].id,a[i].name,a[i].score);}void order(struct student a[10]){    struct student w;w.next=NULL;    for(i=0;i<n-1;i++)        for(j=i+1;j<n;j++)        {            if(a[i].score<a[j].score)            {                w.id=a[i].id;                strcpy(w.name,a[i].name);                w.score=a[i].score;                a[i].id=a[j].id;                strcpy(a[i].name,a[j].name);                a[i].score=a[j].score;                a[j].id=w.id;                strcpy(a[j].name,w.name);                a[j].score=w.score;            }        }}

The input data is 3 and 2 The result of time :

img

img

Expected results :

img

Hope to answer T^T




Refer to the answer 1:

I don't know why you have p1,p2,2 A pointer to the , What are you doing
Before sorting , Print your own list first , See what's in the bottom




Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202022248112718.html

Random recommended