Fixed Makefile.
[libabstract.git] / src / ll.c
blob1ef0c5dcd8c123701411ac346380c9721a054d61
1 /*
2 ll.c - Linked Lists
4 Copyright (c) 2007, Matthew Schmidt <matt.alboin@gmail.com>
6 Permission to use, copy, modify, and distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <stdio.h>
20 #include <stdlib.h>
22 #include "include/alboin.h"
23 #include "include/ll.h"
25 ll *ll_new() {
26 ll *l = malloc(sizeof(ll));
28 l->items = 0;
29 l->fe_started = false;
30 l->next_state = true;
31 l->base = malloc(sizeof(linked_list));
32 l->current = l->base;
34 return l;
37 void ll_add(ll *l, void *a) {
38 l->items++;
40 l->current->data = a;
42 l->current->next = malloc(sizeof(ll));
43 l->current->next->parent = l->current;
44 l->current = l->current->next;
45 l->current->next = NULL;
48 void *ll_remove(ll *l, int item) {
49 int count = 0;
50 foreach(l) {
51 if(count == (item-1)) {
52 linked_list *rem = l->current->next;
53 l->current->next = rem->next;
54 free(rem);
55 l->items--;
56 break;
58 count++;
62 void ll_free(ll *l) {
63 l->current = l->base;
64 while(1) {
65 /* Free the structure. */
66 if(l->current->next == NULL) {
67 free(l->current);
68 break;
70 else {
71 linked_list *tmp = l->current->next;
72 free(l->current);
73 l->current = tmp;
78 void ll_switch(linked_list *l1, linked_list *l2) {
79 void *tmp;
81 tmp = l1->data;
82 l1->data = l2->data;
83 l2->data = tmp;
86 void ll_sort(ll *l, int (*comp)(void*, void*)) {
87 int t = false;
89 while(1) {
90 t = false;
91 l->current = l->base;
93 foreach(l) {
94 int r = comp(l->current->data, l->current->next->data);
95 if(r == 1) {
96 ll_switch(l->current, l->current->next);
97 t = true;
101 if(!t)
102 break;
106 void ll_reset(ll *l) {
107 l->current = l->base;
110 void *ll_foreach(ll *l) {
111 void *ret;
113 /* We have to reset if we haven't already. */
114 if(!l->fe_started) {
115 ll_reset(l);
116 l->fe_started = true;
119 if(!l->next_state)
120 return NULL;
122 ret = l->current->data;
124 if(l->current->next != NULL) {
125 l->current = l->current->next;
126 l->next_state = true;
129 /* We're finished here. Wrap it all up. */
130 else {
131 l->fe_started = false;
132 l->next_state = false;
135 return ret;