applets: fix compile-time warning
[oweals/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 or later, see the file LICENSE in this tarball.
11  */
12
13 #include <stdlib.h>
14 #include "libbb.h"
15
16 /* Add data to the start of the linked list.  */
17 void llist_add_to(llist_t **old_head, void *data)
18 {
19         llist_t *new_head = xmalloc(sizeof(llist_t));
20
21         new_head->data = data;
22         new_head->link = *old_head;
23         *old_head = new_head;
24 }
25
26 /* Add data to the end of the linked list.  */
27 void llist_add_to_end(llist_t **list_head, void *data)
28 {
29         llist_t *new_item = xmalloc(sizeof(llist_t));
30
31         new_item->data = data;
32         new_item->link = NULL;
33
34         if (!*list_head)
35                 *list_head = new_item;
36         else {
37                 llist_t *tail = *list_head;
38
39                 while (tail->link)
40                         tail = tail->link;
41                 tail->link = new_item;
42         }
43 }
44
45 /* Remove first element from the list and return it */
46 void *llist_pop(llist_t **head)
47 {
48         void *data, *next;
49
50         if (!*head)
51                 return NULL;
52
53         data = (*head)->data;
54         next = (*head)->link;
55         free(*head);
56         *head = next;
57
58         return data;
59 }
60
61 /* Unlink arbitrary given element from the list */
62 void llist_unlink(llist_t **head, llist_t *elm)
63 {
64         llist_t *crt;
65
66         if (!(elm && *head))
67                 return;
68
69         if (elm == *head) {
70                 *head = (*head)->link;
71                 return;
72         }
73
74         for (crt = *head; crt; crt = crt->link) {
75                 if (crt->link == elm) {
76                         crt->link = elm->link;
77                         return;
78                 }
79         }
80 }
81
82 /* Recursively free all elements in the linked list.  If freeit != NULL
83  * call it on each datum in the list */
84 void llist_free(llist_t *elm, void (*freeit) (void *data))
85 {
86         while (elm) {
87                 void *data = llist_pop(&elm);
88
89                 if (freeit)
90                         freeit(data);
91         }
92 }
93
94 #ifdef UNUSED
95 /* Reverse list order. */
96 llist_t *llist_rev(llist_t *list)
97 {
98         llist_t *rev = NULL;
99
100         while (list) {
101                 llist_t *next = list->link;
102
103                 list->link = rev;
104                 rev = list;
105                 list = next;
106         }
107         return rev;
108 }
109 #endif