c - Two ways of implementing a linked list: which is better? -


i know 2 ways design generic linked list datastructure in c. , i'm wondering better. before asking question, i'll introduce both methods shortly:

one method build functions around structure following:

struct list_element {     struct list_element *prev;     struct list_element *next;     void *data; }; 

obviously, data pointer points payload. list element struct outside payload. e.g. how glib has designed double linked list facility: http://library.gnome.org/devel/glib/2.26/glib-doubly-linked-lists.html

another method way how it's done in linux kernel: http://isis.poly.edu/kulesh/stuff/src/klist/. there no void pointer payload in list element struct. instead list element struct included in payload struct:

struct list_element {     struct list_element *prev;     struct list_element *next; };  struct person {     char name[20];     unsigned int age;     struct list_element list_entry; }; 

a special macro used pointer payload struct given pointer list_entry, name withing payload struct , type of payload struct (the list_entry() macro).

finally, here question: advantage of latter of 2 methods of constructing linked list? few times i've heard people second more 'generic' first, why? argue first method more generic because payload structures list implementation agnostic, isn't case second method.
1 more downside of second method if want place payload in more 1 list, should struct list_element member each list in payload structure.

edit: summarize far saw 2 answers important me:

  • with first method: removing payload list involves looping through complete list until list element pointing payload found. don't need second method. (answer patrick)
  • with first method have 2 malloc()s each element: 1 payload , 1 list element struct. second method 1 malloc() sufficient. (answer roddy)

the first approach might seem less intrusive in many cases isn't (unless add additional data structures).

imagine have list of thousand persons , want remove 1 of them list. if person doesn't know in list, have scan whole list first exact place of person.

you can solve adding pointer person corresponding list structure, defeats non-intrusiveness (does word exist?) of solution.

another alternative have hash map maps memory addresses of persons memory addresses of list nodes. finding node in list faster (but still slower intrusive way). however, since take more memory, suggest not this.

therefore, easiest , simplest solution second one.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -