summaryrefslogtreecommitdiff
path: root/src/02/04/list.c
blob: cfc3b2c03271102674b3d8a48640a6be407a8805 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "list.h"
#include <stdio.h>
#include <stdlib.h>

Node *list_initialize(void *data) {
  Node *node = malloc(sizeof(Node));
  node->data = data;
  node->next = NULL;
  return node;
}

Node *list_add(Node *head, void *data) {
  Node *tail;
  Node *tmp = head;

  while (tmp) {
    if (!tmp->next)
      break;
    tmp = tmp->next;
  }
  tail = tmp;
  tail->next = list_initialize(data);
  return tail->next;
}

Node *list_get(Node *self, int index) {
  if (!self || index < 0)
    return NULL;

  while (index > 0 && self) {
    self = self->next;
    index--;
  }
  return self;
}

int list_size(Node *head) {
  int i = 0;
  for (Node *tmp = head; tmp && tmp != NULL; tmp = tmp->next)
    i++;
  return i;
}

void list_inspect(Node *self, Printer printer) {
  if (!self)
    return;

  printf("[");
  while (self) {
    printer(self->data);
    self = self->next;
  }
  printf("]\n");
}