1 /* Evil linked-list implementation in C with macros
3 Copyright (C) 1999 Evin Robertson
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
19 The author can be reached at ecr+@andrew.cmu.edu
23 #define LEaddm(list, member, mallocfunc) do { \
24 void *temppointer = list; \
25 list = mallocfunc(sizeof(*list)); \
27 list->next = temppointer; \
30 #define LEadd(list, member) LEaddm(list, member, n_malloc)
32 #define LEremovem(list, freefunc) do { \
34 void *temppointer = list; \
36 freefunc(temppointer); \
40 #define LEremove(list) LEremovem(list, n_free)
43 #define LEdestructm(list, destruct, freefunc) do { \
45 void *temppointer = list; \
48 freefunc(temppointer); \
52 #define LEdestruct(list, destruct) LEdestructm(list, destruct, n_free)
54 #define LEdestroym(list, freefunc) LEdestructm(list, , freefunc)
56 #define LEdestroy(list) LEdestroym(list, n_free)
59 #define LEsearch(list, dest, cond) \
61 for(dest = list; dest; dest=dest->next) \
65 /* temp != NULL if it successfully performed the removal */
66 #define LEsearchremovem(list, dest, temp, cond, destruct, freefunc) \
69 if(dest && (cond)) { \
72 LEremovem(list, freefunc); \
74 for(temp = list; temp; temp=temp->next) { \
76 if(dest && (cond)) { \
77 temp->next = dest->next; \
85 #define LEsearchremove(list, dest, temp, cond, destruct) LEsearchremovem(list, dest, temp, cond, destruct, n_free)
87 #define LEappend(dest, src) do { \
88 void *temppointer = dest; \
102 /* This is just an example: */
106 Use: Declare a struct like this:
109 struct mylist *next; /* The evil linked list library depends on this */
118 mylist *another = NULL;
120 mylist mymember1 = { NULL, 42, "frogs" };
121 mylist mymember2 = { NULL, 38, "potato" };
122 mylist mymember3 = { NULL, 21, "monkey" };
124 LEremove(foo); /* Remove nonexistent head element - this is safe */
126 LEadd(foo, mymember1); /* Add an element to the head */
127 LEadd(foo, mymember2); /* Add another element to the head */
128 LEadd(foo, mymember3);
129 LEadd(foo, mymember1);
131 LEremove(foo); /* Remove the head element */
133 LEsearch(foo, found, (strcmp(found->mystring, "potato") == 0));
135 LEdup(another, found);
139 LEadd(foo, mymember3);
141 LEprepend(another, foo);