i've found this problem very hard to solve solely using *nextName and *nextAge.
Maybe a basic working example of how these structures are used can be of some help..
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_LEN 250
struct node {
char *name;
int age;
struct node *nextName;
struct node *nextAge;
}NODE;
struct node *namestart, *namelast, *info;
struct node *agestart, *agelast;
void StoreNameRecord( struct node *i, /* new element */
struct node **start, /* first element */
struct node **last /* last element */
)
{
struct node *old, *p;
p = *start; /* start at top of list */
if(*last == NULL) /* first element in list */
{
i->nextName = NULL;
*last = i;
*start = i;
return;
}
old = NULL;
while(p)
{
if(stricmp(p->name, i->name) < 0)
{
old = p;
p = p->nextName;
}
else
{
if(old)
{
old ->nextName = i;
i->nextName = p;
return;
}
i->nextName = p; /* new first element */
*start = i;
return;
}
}
(*last)->nextName = i;
i->nextName = NULL;
*last = i;
}
void StoreAgeRecord( struct node *i, /* new element */
struct node **start, /* first element */
struct node **last /* last element */
)
{
struct node *old, *p;
p = *start; /* start at top of list */
if(*last == NULL) /* first element in list */
{
i->nextAge = NULL;
*last = i;
*start = i;
return;
}
old = NULL;
while(p)
{
if(p->age < i->age)
{
old = p;
p = p->nextAge;
}
else
{
if(old)
{
old ->nextAge = i;
i->nextAge = p;
return;
}
i->nextAge = p; /* new first element */
*start = i;
return;
}
}
(*last)->nextAge = i;
i->nextAge = NULL;
*last = i;
}
int main(void)
{
int iIndex, iAge[] = { 23, 10, 45, 16, 99, 14, 34};
char *pNames[] = {"Richard", "Deborah", "Bob", "Alice", "Fred", "Theodore", "Charlie"};
namestart = namelast = info = NULL;
agestart = agelast = NULL;
for(iIndex = 0; iIndex < sizeof(iAge) / sizeof(int); iIndex++)
{
if((info = (struct node *) malloc(sizeof(NODE))) == NULL)
return -1; // Out of memory
if((info->name = (char *) malloc(MAX_LEN * sizeof(char))) == NULL)
return -1;
strcpy(info->name, pNames[iIndex]);
info->age = iAge[iIndex];
if((info->nextName = (struct node *) malloc(sizeof(NODE))) == NULL)
return -1; // Out of memory
if((info->nextAge = (struct node *) malloc(sizeof(NODE))) == NULL)
return -1; // Out of memory
if((info->nextName->name = (char *) malloc(MAX_LEN * sizeof(char))) == NULL)
return -1;
if((info->nextAge->name = (char *) malloc(MAX_LEN * sizeof(char))) == NULL)
return -1;
StoreNameRecord(info, &namestart, &namelast);
StoreAgeRecord(info, &agestart, &agelast);
}
printf("\nPrint sorted by names\n\n");
info = namestart;
while(info) // Beginning to End
{
printf("%-20s %d\n",info->name, info->age);
info = info->nextName;
}
printf("\nPrint sorted by age\n\n");
info = agestart;
while(info) // Beginning to End
{
printf("%-20s %d\n",info->name, info->age);
info = info->nextAge;
}
return 0;
}