linked list of structures

A

Andrew

Are there any problems with creating a linked list of structures in
the following sample? Or is the preferred way to create the data
structure then create a seperate "node" style structure to hold the
data structure and then create a list of the nodes?

#include<stdio.h>
#include<stdlib.h>

struct _listitem {

int a;
int b;
int c;
int d;
int e;
struct _listitem *next;

};

struct _list {
struct _listitem *head;
};

typedef struct _listitem ListItem;
typedef struct _list List;

void Push(List *, ListItem **);
void Destroy(List *);

int main() {

List l;
l.head = 0;

for(int i = 0; i < 10; i++) {

ListItem *newItem;
newItem = (ListItem *)malloc(sizeof(ListItem));

newItem->a = i+1;
newItem->b = i+2;
newItem->c = i+3;
newItem->d = i+4;
newItem->e = i+5;

Push(&l, &newItem);

}

ListItem *tmp;

tmp = l.head;

while(tmp->next) {
tmp = tmp->next;
printf("%i,%i,%i,%i,%i\n",tmp->a,tmp->b,tmp->c,tmp->d,tmp->e);
}

Destroy(&l);

free(&l);

return 0;
}


void Push(List *l, ListItem **n) {

(*n)->next = l->head;
l->head = *n;

}

void Destroy(List *l) {

ListItem *ptr1, *ptr2;

if(!l->head) return;

ptr1 = l->head;
while(ptr1) {
ptr2 = ptr1;
ptr1 = ptr1->next;
free(ptr2);
}

l->head = 0;

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top