StudyPlanner/src/llist.c

87 lines
1.6 KiB
C

#include "llist.h"
#include <stdlib.h>
#include <string.h>
/* create new linked list
* use llistFree after use
* retturns NULL on failure
* otherwise newNode with data as content and cmpFN to compare data
* only use to initialize
* To insert into list use llistAppend
*/
llist *llistNew(void *data, int (*cmpFN)(const void *a, const void *b)) {
llist *r = (llist *)malloc(sizeof(llist));
if (r != NULL) {
r->cmpFn = cmpFN;
r->data = data;
r->prev = NULL;
r->next = NULL;
r->tail = r;
}
return r;
}
/*return last node of linked list;
*/
llist *llistTail(llist *head) {
// llist *tail = head;
// while (tail->next != NULL) {
// tail = tail->next;
// }
return head->tail;
}
/* creates new node from data and appends it to tail
*
*/
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;
head->tail = new;
}
return new;
}
/*
* return Node containing key or NULL
*/
llist *llistGet(llist *head, void *key) {
llist *c = head;
while (c != NULL) {
if (head->cmpFn(c->data, key) == 0) {
return c;
}
c = c->next;
}
return NULL;
}
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;
}
}
/*
* get linked list length
*/
int llistLen(llist *head) {
int len = 0;
llist *c = head;
while (c != NULL) {
len += 1;
c = c->next;
}
return len;
}