C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
data_structures/linked_list/main.c
Go to the documentation of this file.
1/**
2 * @file main.c
3 * @brief Linked-list CLI demo.
4 *
5 * Reads numbers from argv, builds a list (push_back), prints it, finds
6 * the first arg, reverses, prints again. Demonstrates all the core ops.
7 */
8
9#include "linked_list.h"
10#include <stdio.h>
11#include <stdlib.h>
12
13static void print_list(const linked_list_t *list, const char *label) {
14 printf("%s (size=%zu): [", label, ll_size(list));
15 for (const ll_node_t *cur = list->head; cur; cur = cur->next) {
16 printf("%d", cur->value);
17 if (cur->next) printf(" → ");
18 }
19 printf("]\n");
20}
21
22int main(int argc, char *argv[]) {
23 if (argc < 2) {
24 printf("Usage: %s <num1> <num2> ...\n", argv[0]);
25 printf("Example: %s 1 2 3 4 5\n", argv[0]);
26 return EXIT_FAILURE;
27 }
28
29 linked_list_t *list = ll_create();
30 if (!list) return EXIT_FAILURE;
31
32 for (int i = 1; i < argc; i++) {
33 if (!ll_push_back(list, atoi(argv[i]))) {
34 fprintf(stderr, "out of memory\n");
35 ll_destroy(list);
36 return EXIT_FAILURE;
37 }
38 }
39
40 print_list(list, "Built");
41
42 int target = atoi(argv[1]);
43 size_t idx = ll_find(list, target);
44 if (idx == LL_NOT_FOUND) {
45 printf("find(%d): not found\n", target);
46 } else {
47 printf("find(%d): index %zu\n", target, idx);
48 }
49
50 ll_reverse(list);
51 print_list(list, "Reversed");
52
53 ll_destroy(list);
54 return EXIT_SUCCESS;
55}
int main(void)
Definition benchmark.c:50
static void print_list(const linked_list_t *list, const char *label)
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
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