master
 1#include "list.h"
 2#include <stdio.h>
 3#include <stdlib.h>
 4
 5/**
 6 * Initializes a new node for a linked list.
 7 *
 8 * @param data The data to bind to the new node in the list.
 9 * @return Returns a new linked list node
10 */
11Node *list_initialize(void *data) {
12  Node *node = malloc(sizeof(Node));
13  node->data = data;
14  node->next = NULL;
15  return node;
16}
17
18/**
19 * Adds a new item to the tail of a linked list
20 *
21 * @param head The head of a linked list
22 * @param data The data to add to the tail of a linked list
23 * @return Returns the new node tail node
24 */
25Node *list_add(Node *head, void *data) {
26  Node *tail;
27  Node *tmp = head;
28
29  while (tmp) {
30    if (!tmp->next)
31      break;
32    tmp = tmp->next;
33  }
34  tail = tmp;
35  tail->next = list_initialize(data);
36  return tail->next;
37}
38
39/**
40 * Returns a specific node by zero based index in a linked list.
41 *
42 * @param self the head of the linked list
43 * @param index the offset from the head of the node to return
44 * @return Returns the node at the specified offset or NULL.
45 */
46Node *list_get(Node *self, int index) {
47  if (!self || index < 0)
48    return NULL;
49
50  while (index > 0 && self) {
51    self = self->next;
52    index--;
53  }
54  return self;
55}
56
57/**
58 * Returns the total number of nodes in a linked list.
59 *
60 * @param head The head of a linked list
61 * @returns Returns the # of items in the list.
62 */
63int list_size(Node *head) {
64  int i = 0;
65  for (Node *tmp = head; tmp && tmp != NULL; tmp = tmp->next)
66    i++;
67  return i;
68}
69
70/**
71 * Prints a visual representation of a linked list.
72 *
73 * @param self The head of the linked list
74 * @param printer A callback function to invoke to print each item.
75 */
76void list_inspect(Node *self, Printer printer) {
77  if (!self)
78    return;
79
80  printf("[");
81  while (self) {
82    printer(self->data);
83    self = self->next;
84  }
85  printf("]\n");
86}