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;
}
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;
}