Example
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct info {
char name[20];
struct info *next;
} info;
/* List Functions */
/* -------------- */
info *newnode ( void ) {
info *new = malloc( sizeof *new );
if ( new ) {
new->next = NULL;
}
return new;
}
info *list_prepend ( info *head, char *name ) {
info *new = newnode( );
if ( new ) {
new->next = head;
strcpy( new->name, name );
}
return new;
}
void list_print ( info *head ) {
while ( head ) {
printf( "%s\n", head->name );
head = head->next;
}
}
int list_count ( info *head ) {
int result = 0;
while ( head ) {
result++;
head = head->next;
}
return result;
}
int compare ( const void *a, const void *b ) {
info * const *pa = a;
info * const *pb = b;
return strcmp( (*pa)->name, (*pb)->name );
}
info *list_sort ( info *head ) {
int i, n;
info **array;
/* create array out of a list */
n = list_count( head );
array = malloc( n * sizeof *array );
for ( i = 0 ; i < n ; i++ ) {
array[i] = head;
head = head->next;
}
/* sort it */
qsort( array, n, sizeof(array[0]), compare );
/* create list out of array */
for ( i = 0 ; i < n-1 ; i++ ) {
array[i]->next = array[i+1];
}
array[n-1]->next = NULL;
head = array[0];
free( array );
return head;
}
int main ( ) {
info *list = NULL;
char *names[] = { "now", "is", "the", "time", "for", "all", "to", "party" };
int i;
/* create a list */
for ( i = 0 ; i < sizeof(names)/sizeof(names[0]) ; i++ ) {
list = list_prepend( list, names[i] );
}
printf( "Unsorted\n" );
list_print( list );
printf( "\nsorted\n" );
list = list_sort( list );
list_print( list );
return 0;
}