104 lines
1.6 KiB
C
104 lines
1.6 KiB
C
#include "linked_list.h"
|
|
|
|
#include <stdlib.h>
|
|
#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;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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);
|
|
} |