2024-12-11 03:10:11 +01:00
|
|
|
#include "llist.h"
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
/* create new linked list
|
|
|
|
* use llistFree after use
|
|
|
|
* retturns NULL on failure
|
|
|
|
*/
|
|
|
|
llist *llistNew(void *data, int (*cmpFN)(void *a, void *b)) {
|
|
|
|
llist *r = (llist *)malloc(sizeof(llist));
|
|
|
|
if (r != NULL) {
|
|
|
|
r->cmpFn = cmpFN;
|
|
|
|
r->data = data;
|
|
|
|
r->prev = NULL;
|
|
|
|
r->next = NULL;
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*return last node of linked list;
|
|
|
|
*/
|
|
|
|
llist *llistTail(llist *l) {
|
|
|
|
llist *tail = l;
|
|
|
|
while (tail->next != NULL) {
|
|
|
|
tail = tail->next;
|
|
|
|
}
|
|
|
|
return tail;
|
|
|
|
}
|
|
|
|
|
2024-12-11 11:01:37 +01:00
|
|
|
/* creates new node from data and appends it to tail
|
2024-12-11 03:10:11 +01:00
|
|
|
*
|
|
|
|
*/
|
|
|
|
llist *llistAppend(llist *head, void *data) {
|
|
|
|
llist *new = llistNew(data, head->cmpFn);
|
|
|
|
if (new != NULL) {
|
|
|
|
llist *tail = llistTail(head);
|
|
|
|
new->data = data;
|
|
|
|
new->next = NULL;
|
|
|
|
new->prev = tail;
|
|
|
|
tail->next = new;
|
|
|
|
}
|
|
|
|
return new;
|
|
|
|
}
|
|
|
|
|
2024-12-11 11:01:37 +01:00
|
|
|
/*
|
|
|
|
* return Node containing key or NULL
|
|
|
|
*/
|
|
|
|
llist *llistGet(llist *head, void *key) {
|
2024-12-11 03:10:11 +01:00
|
|
|
llist *c = head;
|
|
|
|
while (c != NULL) {
|
2024-12-11 11:13:45 +01:00
|
|
|
if (head->cmpFn(c->data, key) == 0) {
|
2024-12-11 03:10:11 +01:00
|
|
|
return c;
|
|
|
|
}
|
|
|
|
c = c->next;
|
|
|
|
}
|
|
|
|
return NULL;
|
|
|
|
}
|
2024-12-11 11:01:37 +01:00
|
|
|
|
2024-12-11 03:10:11 +01:00
|
|
|
bool llistContains(llist *head, void *key) {
|
|
|
|
return llistGet(head, key) != NULL;
|
|
|
|
}
|
|
|
|
void llistFree(llist *head) {
|
|
|
|
while (head != NULL) {
|
|
|
|
llist *tmp = head->next;
|
|
|
|
free(head);
|
|
|
|
head = tmp;
|
|
|
|
}
|
|
|
|
}
|