#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
struct node *next;
char fname[20];
char lname[20];
int age;
} node_t;
// list append function, which you should have already
node_t *append ( node_t *head, char fname[], char lname[], int age ) {
node_t *newnode = malloc ( sizeof *newnode );
newnode->next = NULL;
strcpy( newnode->fname, fname );
strcpy( newnode->lname, lname );
newnode->age = age;
if ( head == NULL ) {
head = newnode;
} else {
node_t *temp = head;
while ( temp->next != NULL ) temp = temp->next;
temp->next = newnode;
}
return head;
}
// list length, which you may have already
int length ( node_t *head ) {
int count = 0;
while ( head != NULL ) {
head = head->next;
count++;
}
return count;
}
// create an array of pointers to each member of the list
void copy_ptrs ( node_t *head, node_t **arr ) {
int count = 0;
while ( head != NULL ) {
arr[count++] = head;
head = head->next;
}
}
// example compare functions
int cmp_fname ( const void *pa, const void *pb ) {
const node_t **a = pa;
const node_t **b = pb;
return strcmp( (*a)->fname, (*b)->fname );
}
int cmp_age ( const void *pa, const void *pb ) {
const node_t **a = pa;
const node_t **b = pb;
int ia = (*a)->age;
int ib = (*b)->age;
if ( ia < ib ) return -1;
if ( ia > ib ) return +1;
return 0;
}
int main(void) {
int list_len, i;
node_t *list = NULL;
node_t **array;
// create a list
list = append( list, "fred", "flintstone", 35 );
list = append( list, "wilma", "flintstone", 33 );
list = append( list, "pebbles", "flintstone", 5 );
list = append( list, "barney", "rubble", 29 );
list = append( list, "betty", "rubble", 27 );
list = append( list, "bam-bam", "rubble", 4 );
// flatten the current list into an array
list_len = length( list );
array = malloc ( list_len * sizeof *array );
copy_ptrs ( list, array );
// having got an array, you can qsort() it multiple times
// without any further difficulty.
qsort( array, list_len, sizeof *array, cmp_fname );
for ( i = 0 ; i < list_len; i++ ) {
printf( "%s %s %d\n", array[i]->fname, array[i]->lname, array[i]->age );
}
qsort( array, list_len, sizeof *array, cmp_age );
for ( i = 0 ; i < list_len; i++ ) {
printf( "%s %s %d\n", array[i]->fname, array[i]->lname, array[i]->age );
}
return 0;
}