Bug fix from Vladimir Oleynik, and suggestion I add my copyright notice
[platform/upstream/busybox.git] / libbb / llist.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * linked list helper functions.
4  *
5  * Copyright (C) 2003 Glenn McGrath
6  * Copyright (C) 2005 Vladimir Oleynik
7  * Copyright (C) 2005 Bernhard Fischer
8  * Copyright (C) 2006 Rob Landley <rob@landley.net>
9  *
10  * Licensed under the GPL v2, see the file LICENSE in this tarball.
11  */
12 #include <stdlib.h>
13 #include "libbb.h"
14
15 #ifdef L_llist_add_to
16 /* Add data to the start of the linked list.  */
17 llist_t *llist_add_to(llist_t *old_head, char *new_item)
18 {
19         llist_t *new_head;
20
21         new_head = xmalloc(sizeof(llist_t));
22         new_head->data = new_item;
23         new_head->link = old_head;
24
25         return (new_head);
26 }
27 #endif
28
29 #ifdef L_llist_add_to_end
30 /* Add data to the end of the linked list.  */
31 llist_t *llist_add_to_end(llist_t *list_head, char *data)
32 {
33         llist_t *new_item;
34
35         new_item = xmalloc(sizeof(llist_t));
36         new_item->data = data;
37         new_item->link = NULL;
38
39         if (list_head == NULL) {
40                 list_head = new_item;
41         } else {
42                 llist_t *tail = list_head;
43                 while (tail->link)
44                         tail = tail->link;
45                 tail->link = new_item;
46         }
47         return list_head;
48 }
49 #endif
50
51 #ifdef L_llist_pop
52 /* Remove first element from the list and return it */
53 void *llist_pop(llist_t **head)
54 {
55         void *data;
56
57         if(!*head) data = *head;
58         else {
59                 void *next = (*head)->link;
60                 data = (*head)->data;
61                 free(*head);
62                 *head = next;
63         }
64
65         return data;
66 }
67 #endif
68
69 #ifdef L_llist_free
70 /* Recursively free all elements in the linked list.  If freeit != NULL
71  * call it on each datum in the list */
72 void llist_free(llist_t *elm, void (*freeit)(void *data))
73 {
74         while (elm) {
75                 void *data = llist_pop(&elm);
76                 if (freeit) freeit(data);
77         }
78 }
79 #endif