linked list of structures

Discussion in 'C Programming' started by Andrew, Aug 11, 2003.

  1. Andrew

    Andrew Guest

    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;

    }
     
    Andrew, Aug 11, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Patrick McCourt

    Stack & Singly Linked List Data Structures

    Patrick McCourt, May 24, 2004, in forum: Java
    Replies:
    2
    Views:
    969
    Kenneth P. Turvey
    May 24, 2004
  2. Chris Ritchey
    Replies:
    7
    Views:
    513
    emerth
    Jul 10, 2003
  3. Alfonso Morra
    Replies:
    11
    Views:
    754
    Emmanuel Delahaye
    Sep 24, 2005
  4. fool
    Replies:
    14
    Views:
    544
    Barry Schwarz
    Jul 3, 2006
  5. joshd
    Replies:
    12
    Views:
    702
    John Carson
    Oct 2, 2006
Loading...

Share This Page