河岸柳 发表于 2022-1-6 00:31:14

如何实现链表字符串交换?

如何实现数字从大到小排序的同时,数字前面的名字也随着数字排序?
        #include<stdio.h>
        FILE *in,*out;
        typedef struct
        {
          double x;
          char name;
        }STU;
        STU stu;
        int cmp(const void *a,const void *b)
        {
          return ((STU*)a)->x > ((STU*)b)->x ? -1:1;
        }
        int main()
        {
          int n,i,temp;
          char temp_name;
          char name;
          in=fopen("use.txt","r");
          out=fopen("B.txt","w");
          n=0;
          while(fscanf(in,"%s%lf,",stu.name,&stu.x)!=EOF)
          n++;
                for (int j = 0; j < n - 1; j++)
                {
                        for (int i = 0; i < n - 1 - j; i++)
                        if (stu.x < stu.x)
                        {
                                temp = stu.x;
                                stu.x = stu.x;
                                stu.x = temp;
                        }
                }
          for(i=0;i<n;i++)
          fprintf(out,"%s %lf\n",stu.name,stu.x);
          fclose(in);
          fclose(out);
          return 0;
        }

傻眼貓咪 发表于 2022-1-6 09:05:48

本帖最后由 傻眼貓咪 于 2022-1-6 09:17 编辑

#include <stdio.h>
#include <stdlib.h>

typedef struct{
        int id;
        char name;
}fruit;

int compare(const void *a, const void *b){
        fruit *x = (fruit *)a;
        fruit *y = (fruit *)b;
        return (x->id - y->id);
}

int main()
{
        fruit arr = {
                {2, "banana"},
                {7, "oren"},
                {3, "apple"},
                {4, "watermelon"},
                {6, "strawberry"}
        };
        qsort(arr, 5, sizeof(fruit), compare);
       
        for(int i = 0; i < 5; i++) printf("id:%d fruit:%s\n", arr.id, arr.name);
        return 0;
}
页: [1]
查看完整版本: 如何实现链表字符串交换?