How do I sort a linked list of structures by one of the fields?

前端 未结 4 2043
孤城傲影
孤城傲影 2021-01-15 08:24

Wow now i know I dont. Lol.

I\'ve got my structure like this:

struct Medico{ 
int Id_Doctor;
int Estado;
char Nombre[60]; ////focus on this part of t         


        
4条回答
  •  深忆病人
    2021-01-15 09:11

    Implementing a mergesort over a linked list in C is quite easy:

    #include 
    #include 
    #include 
    
    struct node {
        struct node *next;
        char *data;
    };
    
    struct node *
    divlist (struct node *n) {
        int i = 0;
        if (n) {
            struct node *tail, *n2 = n;
            while (1) {
                n2 = n2->next;
                if (!n2) break;
                if (i++ & 1) n = n->next;
            }
            tail = n->next;
            n->next = NULL;
            return tail;
        }
        return NULL;
    }
    
    struct node *
    mergelists(struct node *a, struct node *b) {
        struct node *n;
        struct node **last = &n;
        if (!a) return b;
        if (!b) return a;
    
        while (1) {
            if (strcmp(a->data, b->data) > 1) {
                *last = b;
                last = &b->next;
                b = b->next;
                if (!b) {
                    *last = a;
                    break;
                }
            }
            else {
                *last = a;
                last = &a->next;
                a = a->next;
                if (!a) {
                    *last = b;
                    break;
                }
            }
        }
        return n;
    }
    
    struct node *
    sortlist (struct node *n) {
        struct node *tail = divlist(n);
        if (!tail) return n;
        return mergelists(sortlist(n), sortlist(tail));
    }
    
    int main(int argc, char *argv[]) {
        int i;
        struct node *n1, *n = NULL;
        for (i = argc; --i >= 1;) {
            n1 = (struct node *)malloc(sizeof(*n1));
            n1->data = argv[i];
            n1->next = n;
            n = n1;
        }
    
        n1 = n = sortlist(n);
    
        while (n1) {
            printf("%s\n", n1->data);
            n1 = n1->next;
        }
        return 0;
    }
    

    Note that you will have to modify this code to use your data structure and the right comparison!

提交回复
热议问题