Archived
1
This repository has been archived on 2020-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
linked-list/Implementation/linked_list.c

86 lines
1.2 KiB
C

#include "linked_list.h"
#include <stdlib.h>
static Node* create(void* data)
{
Node* node = calloc(1, sizeof(Node));
if (!node)
return NULL;
node->data = data;
return node;
}
void list_print(Node* head, void (*print_func)(void*))
{
while (head)
{
print_func(head->data);
head = head->next;
}
}
void list_push(Node** head, void* data)
{
Node* node = create(data);
if (!node)
return;
node->next = *head;
if (*head)
(*head)->prev = node;
*head = node;
}
void list_append(Node** head, void* data)
{
Node* node = create(data), *end;
if (!node)
return;
if (!*head)
*head = node;
else
{
end = *head;
while (end->next)
end = end->next;
end->next = node;
node->prev = end;
}
}
void list_insert(Node* prev_node, void* data)
{
Node* node = create(data);
if (!node)
return;
node->next = prev_node->next;
node->prev = prev_node;
prev_node->next = node;
if (node->next)
node->next->prev = node;
}
Node* list_get(Node* head, unsigned index)
{
while (head && index--)
head = head->next;
return head;
}
void list_remove(Node* node)
{
if (node->prev)
node->prev->next = node->next;
if (node->next)
node->next->prev = node->prev;
free(node);
}