alphabetically sorted linked list

ronenk_at_tauex.tau.ac.il
Date: 12/17/04


Date: 17 Dec 2004 01:27:04 -0800

Hi,
I'm trying to build an alphabetically sorted linked list. This is what
I got so far:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TOTAL 10
typedef struct name
{
char FName[10];
char LName[10];
struct name *next;
} NAMES;
NAMES allNanes[TOTAL]=
{
{"Bill", "Jordan"},
{"Josh", "Williams"},
{"Jessy", "Brown"},
{"Gully", "Portman"}
};

NAMES *new_node(void)
{
return malloc(sizeof(NAMES));
}

void insert_node(NAMES *list, NAMES *node)
{
NAMES *l, *lprev = NULL;

l=list;

if(strcmp (l->FName , node->FName)<0)
break; //I know it's illigal! but what do I put
//here instead?

lprev = l;

// lprev will be NULL if the node should be inserted at the head

// of the list
if(lprev)
{
node->next = lprev->next;
lprev->next = node;
}
else
{ // Make node the new head of the list
node->next = list->next;
list = node;
}
}

int main(void)
{
int i;
NAMES *list=NULL, *t;

for(i = 0;i < 10;++i)
{
t = new_node();
t = allNanes;
insert_node(list, t);
}

for(t = list;t;t = t->next)
printf("%s\t%s", t->FName, t->LName);
printf ("\n");

return 0;
}

The problem is apparently within the function insert_node & I have
specified it with notes in the code.
please review and advice how to fix it.

TIA,

Ronen



Relevant Pages