简体   繁体   中英

sort a linked list of struct in c

I am trying to sort a linked list in an ascending order according to the element of the struct"capacite". But it doesn't give a result. What is the mistake i am making? Here is my code

typedef struct avion avion;

typedef avion*  aliste;

struct avion
{
    char code[20];
    int capacite;
    char etat;
    int date;
    int nvols;
    aliste svt;
};

i have created the list. and following the function that sort it:

void tri(aliste L)
{
   aliste i,j,min,tmp;
   for (i=L; i->svt != NULL; i=i->svt)
   {
      min=i;
      for (j=i->svt; j != NULL; j=j->svt)
      {
        if (j->capacite < min->capacite)
           min=j;
      }
       if (min != i)
      {
       tmp=min;
       min=i;
       i=tmp;
      }
    }
}

It looks like you are trying to bubble sort your list. A quick and dirty fix would be to swap the contents of your nodes:

void tri(aliste L)
{
   aliste i,j,min;
   avion tmp;
      ...
      if (min != i)
      {
       tmp=*min;
       *min=*i;
       *i=tmp;
      }
    }
}

The good news here is that the L pointer passed from the caller still points to the beginning of the list. The downside if that it copies the structures while changing only the svt pointers would be much more efficient. But:

  • you will have to return to the caller a pointer to the new head
  • moving elements from a singly linked list requires to record the previous element

As you use bubble sort which is not a very efficient algorithme, I assume that you only intend to process small lists and that performance is not essential, so you are on your own...

A common way to implement a linked list of structs in C is in https://www.geeksforgeeks.org/linked-list-set-1-introduction/

Basically inside the struct there is a pointer next to the next node in the linked list, what establishes the linked list functionality:

struct Node { 
    int data; 
    struct Node* next; 
}; 

For this more common implementation of a linked list in C you find source code for many sorting algorithms (qsort, mergesort,...) on the net. You have to implement functionality for more than one parameter in such an example because your nodes (of the linked list) have multiple data fields...

Sorting linked list by multiple parameters

typedef avion* aliste; Is it a good idea to typedef pointers?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM