breakhack/src/linkedlist.c

127 lines
2.0 KiB
C
Raw Normal View History

2017-11-30 21:00:47 +01:00
#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
#include "util.h"
2017-11-30 21:00:47 +01:00
static
LinkedList* linkedlist_node_create(void)
2017-11-30 21:00:47 +01:00
{
LinkedList *newList = ec_malloc(sizeof(LinkedList));
2017-11-30 21:00:47 +01:00
newList->next = NULL;
newList->data = NULL;
return newList;
}
2017-12-19 22:51:00 +01:00
LinkedList* linkedlist_create(void)
2017-11-30 21:00:47 +01:00
{
return NULL;
}
void linkedlist_push(LinkedList **head, void *value)
2017-11-30 21:00:47 +01:00
{
LinkedList *node = linkedlist_node_create();
node->data = value;
2017-11-30 21:00:47 +01:00
node->next = *head;
*head = node;
}
void* linkedlist_pop(LinkedList **head)
{
if (*head == NULL)
return NULL;
void *data = (*head)->data;
LinkedList *oldHead = *head;
*head = (*head)->next;
free(oldHead);
return data;
}
void linkedlist_append(LinkedList **head, void *value)
2017-11-30 21:00:47 +01:00
{
LinkedList *node;
2017-11-30 21:00:47 +01:00
if (*head == NULL) {
*head = linkedlist_node_create();
(*head)->data = value;
return;
2017-11-30 21:00:47 +01:00
}
node = *head;
while (node->next != NULL)
node = node->next;
node->next = linkedlist_node_create();
node->next->data = value;
2017-11-30 21:00:47 +01:00
}
void* linkedlist_poplast(LinkedList **head)
{
if (*head == NULL)
return NULL;
if ((*head)->next == NULL) {
void* data = (*head)->data;
free(*head);
*head = NULL;
return data;
}
LinkedList *nextNode = (*head)->next;
if (nextNode->next == NULL) {
void *data = nextNode->data;
free((*head)->next);
(*head)->next = NULL;
return data;
}
return linkedlist_poplast(&nextNode);
}
void* linkedlist_get(LinkedList **head, unsigned int index)
{
if (*head == NULL)
return NULL;
if (index == 0)
return (*head)->data;
return linkedlist_get(&(*head)->next, --index);
}
void linkedlist_each(LinkedList **head, void (*fun)(void*))
{
LinkedList *next = *head;
while (next != NULL) {
fun(next->data);
next = next->next;
}
}
2017-11-30 21:00:47 +01:00
void linkedlist_destroy(LinkedList **head)
{
if (*head == NULL) {
return;
}
linkedlist_destroy(&(*head)->next);
2017-11-30 21:00:47 +01:00
2017-12-15 08:08:45 +01:00
if ((*head)->data != NULL) {
free((*head)->data);
(*head)->data = NULL;
}
2017-11-30 21:00:47 +01:00
free(*head);
*head = NULL;
}
unsigned int linkedlist_size(LinkedList *head)
{
if (head == NULL) {
return 0;
}
return 1 + linkedlist_size(head->next);
}