C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
linked_list.c
Go to the documentation of this file.
1/**
2 * @file linked_list.c
3 */
4
5#include "linked_list.h"
6#include <stdlib.h>
7
9 linked_list_t *list = malloc(sizeof(*list));
10 if (!list) return NULL;
11 list->head = NULL;
12 list->size = 0;
13 return list;
14}
15
17 if (!list) return;
18 ll_node_t *cur = list->head;
19 while (cur) {
20 ll_node_t *next = cur->next;
21 free(cur);
22 cur = next;
23 }
24 free(list);
25}
26
27bool ll_push_front(linked_list_t *list, int value) {
28 if (!list) return false;
29 ll_node_t *node = malloc(sizeof(*node));
30 if (!node) return false;
31 node->value = value;
32 node->next = list->head;
33 list->head = node;
34 list->size++;
35 return true;
36}
37
38bool ll_push_back(linked_list_t *list, int value) {
39 if (!list) return false;
40 ll_node_t *node = malloc(sizeof(*node));
41 if (!node) return false;
42 node->value = value;
43 node->next = NULL;
44
45 if (!list->head) {
46 list->head = node;
47 } else {
48 ll_node_t *cur = list->head;
49 while (cur->next) cur = cur->next;
50 cur->next = node;
51 }
52 list->size++;
53 return true;
54}
55
56bool ll_pop_front(linked_list_t *list, int *out_value) {
57 if (!list || !list->head) return false;
58 ll_node_t *node = list->head;
59 if (out_value) *out_value = node->value;
60 list->head = node->next;
61 free(node);
62 list->size--;
63 return true;
64}
65
66size_t ll_find(const linked_list_t *list, int value) {
67 if (!list) return LL_NOT_FOUND;
68 size_t idx = 0;
69 for (ll_node_t *cur = list->head; cur; cur = cur->next, idx++) {
70 if (cur->value == value) return idx;
71 }
72 return LL_NOT_FOUND;
73}
74
75size_t ll_size(const linked_list_t *list) {
76 return list ? list->size : 0;
77}
78
79bool ll_is_empty(const linked_list_t *list) {
80 return !list || list->size == 0;
81}
82
84 if (!list) return;
85 ll_node_t *prev = NULL;
86 ll_node_t *cur = list->head;
87 while (cur) {
88 ll_node_t *next = cur->next;
89 cur->next = prev;
90 prev = cur;
91 cur = next;
92 }
93 list->head = prev;
94}
bool ll_is_empty(const linked_list_t *list)
Definition linked_list.c:79
size_t ll_size(const linked_list_t *list)
Definition linked_list.c:75
size_t ll_find(const linked_list_t *list, int value)
Definition linked_list.c:66
void ll_reverse(linked_list_t *list)
Definition linked_list.c:83
bool ll_pop_front(linked_list_t *list, int *out_value)
Definition linked_list.c:56
bool ll_push_front(linked_list_t *list, int value)
Definition linked_list.c:27
void ll_destroy(linked_list_t *list)
Definition linked_list.c:16
bool ll_push_back(linked_list_t *list, int value)
Definition linked_list.c:38
linked_list_t * ll_create(void)
Definition linked_list.c:8
Singly-linked list of int.
#define LL_NOT_FOUND
Definition linked_list.h:49
ll_node_t * head
Definition linked_list.h:30
struct ll_node * next
Definition linked_list.h:26
int value
Definition linked_list.h:25