#include <stdio.h>
#include <stdlib.h>
//#include "list.h"
typedef struct s_list
{
int data;
struct s_list *next;
} t_list;
// ici pas dans le code de base
int ascending(int a, int b)
{
return (a <= b);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
t_list *sort_list(t_list* lst, int (*cmp)(int, int))
{
t_list *curr;
int swapped = 1;
// ne pas oublier de vérifier si lst est valide
if (lst == NULL)
return NULL;
while (swapped)
{
swapped = 0; // ne pas oublier de mettre a 0 sinon boucle infini !!!
curr = lst;
// il faut mtn parcourir la liste
while (curr->next != NULL) // Attention NULL pas '\0'
{
// comparer les élément et échanger si néceassire
if ((*cmp)(curr->data, curr->next->data) == 0)
{
swap(&curr->data, &curr->next->data); // a retenir la syntax
swapped = 1;
}
curr = curr->next;
}
}
return lst;
}
// main pour le test
// creat ellement
// print list
t_list *creat_elem(int value)
{
t_list *new_elem;
new_elem = malloc(sizeof(t_list));
if (new_elem == NULL)
return NULL;
new_elem->data = value; // ajouter la valeur au node dans data
new_elem->next = NULL; //
return new_elem;
}
void print_list(t_list *head)
{
while (head)
{
printf("%d\n", head->data);
head = head->next;
}
printf("\n");
}
int main()
{
t_list *my_list;
my_list = creat_elem(3);
my_list->next = creat_elem(1);
my_list->next->next = creat_elem(0);
my_list->next->next->next= creat_elem(100);
my_list->next->next->next->next = creat_elem(-7);
printf("Avant le tri: \n");
print_list(my_list);
sort_list(my_list, ascending);
printf("Après le tri: \n");
print_list(my_list);
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: