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

104 lines
1.6 KiB
C
Raw Normal View History

#include "linked_list.h"
#include <stdlib.h>
2020-01-30 07:48:20 +01:00
#include <stdio.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;
}
}
2020-01-30 07:48:20 +01:00
void list_print_pointers(Node* head)
{
printf("%-19s%-19s%-19s%-19s\n", "Prev", "Current", "Next", "Data");
while (head)
{
printf("0x%p 0x%p 0x%p 0x%p\n", head->prev, head, head->next, 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;
}
2020-01-30 08:28:13 +01:00
Node* list_search(Node* head, void* elem, int (*eq)(void*, void*))
{
while (head && !eq(elem, head->data))
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);
}