James wrote:
> i've got several linked lists in my program they _all_ have 1 or more
> data elements and a next pointer that points to the next item in the list
> or NULL if the end.
> For this example, let's assume i've got 3 linked lists:
[snipped]
> can i make it so i only have 1 display and 1 add function that works for
> ALL the lists? so all i have to do is call Add with the data (the actual
> code in each add function is identical except for the list data type and
> the input data)
>
> i thought about something like this:
>
> void DisplayList (void *list);
>
> then to use it you cast the void to whatever list type you're using, but
> that's as far as i got.
>
> [this reads a bit like an exam question doesn't it!]
You could do this by either:
a) Make the `next' pointer the first pointer in the list, so that you
can traverse the list without needing to know anything about the
remaining data.
b) Dynamically allocate the data, and have a generic node structure
which just contains a `void *' as the data member, i.e.
typedef struct list {
void *data;
struct list *next;
} list;
c) Make the node structure contain a union of the possible types, e.g.
typedef struct list {
struct list *next;
union {
int i;
float f;
struct {
list *item;
list *item2;
} s;
} data;
} list;
As for printing the list, I would pass a callback which prints each
node, e.g.
void print_list(list *l, void (*printfn)(list *))
{
for ( ; l; l = l->next)
(*printfn)(l);
}
For case a), the individual print functions can cast their argument to
the appropriate type. For case b), they would cast the `data' field to
the appropriate type. For case c), they would use the appropriate
member of the union.
--
Glynn Clements <[EMAIL PROTECTED]>