summaryrefslogtreecommitdiff
path: root/src/02/04/list.c
blob: 1de7a03bfff13dd1528b1be0292e7d7fc1004362 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "list.h"
#include <stdio.h>
#include <stdlib.h>

/**
 * Initializes a new node for a linked list.
 *
 * @param data The data to bind to the new node in the list.
 * @return Returns a new linked list node
 */
Node *list_initialize(void *data) {
  Node *node = malloc(sizeof(Node));
  node->data = data;
  node->next = NULL;
  return node;
}

/**
 * Adds a new item to the tail of a linked list
 *
 * @param head The head of a linked list
 * @param data The data to add to the tail of a linked list
 * @return Returns the new node tail 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;
}

/**
 * Returns a specific node by zero based index in a linked list.
 *
 * @param self the head of the linked list
 * @param index the offset from the head of the node to return
 * @return Returns the node at the specified offset or NULL.
 */
Node *list_get(Node *self, int index) {
  if (!self || index < 0)
    return NULL;

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

/**
 * Returns the total number of nodes in a linked list.
 *
 * @param head The head of a linked list
 * @returns Returns the # of items in the list.
 */
int list_size(Node *head) {
  int i = 0;
  for (Node *tmp = head; tmp && tmp != NULL; tmp = tmp->next)
    i++;
  return i;
}

/**
 * Prints a visual representation of a linked list.
 *
 * @param self The head of the linked list
 * @param printer A callback function to invoke to print each item.
 */
void list_inspect(Node *self, Printer printer) {
  if (!self)
    return;

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