master
  1#include "singly_linked_list.h"
  2#include <stdio.h>
  3#include <stdlib.h>
  4
  5/**
  6 * The equivalent of a constructor to initalize a linked list.
  7 *
  8 * @param data The initial data to seed the linked list
  9 * @return Returns a new Node
 10 */
 11Node *initialize(int data) {
 12  Node *node = malloc(sizeof(Node));
 13  node->data = data;
 14  node->next = NULL;
 15  return node;
 16}
 17
 18/**
 19 * Add a node to the tail of the linked list
 20 *
 21 * @param head The head of the linked list
 22 * @param data The data to add to the linked list
 23 */
 24Node *add(Node *head, int data) {
 25  Node *tail;
 26  Node *tmp = head;
 27
 28  while (tmp) {
 29    if (!tmp->next)
 30      break;
 31    tmp = tmp->next;
 32  }
 33  tail = tmp;
 34  tail->next = initialize(data);
 35  return tail->next;
 36}
 37
 38/**
 39 * Gets a specific node by index starting from index 0.
 40 *
 41 * @param self The Node to start from
 42 * @param index The index of the node to return
 43 * @return The node at the specific index
 44 */
 45Node *get(Node *self, int index) {
 46  if (!self || index < 0)
 47    return NULL;
 48
 49  while (index > 0 && self) {
 50    self = self->next;
 51    index--;
 52  }
 53  return self;
 54}
 55
 56/**
 57 * Counts the number of items in the linked list
 58 *
 59 * @param head The head of the linked list
 60 * @return The # of items in the linked list
 61 */
 62static int size(Node *head) {
 63  int i = 0;
 64  for (Node *tmp = head; tmp && tmp != NULL; tmp = tmp->next)
 65    i++;
 66  return i;
 67}
 68
 69/**
 70 * Swaps nodes in a linked list that are in positions
 71 * x and y.
 72 *
 73 * @param head The head of the linked list
 74 * @param x The node in position x
 75 * @param y The node in position y
 76 */
 77void swap(Node **head, int x, int y) {
 78  int count = size(*head);
 79
 80  if (x == y)
 81    return;
 82  if (x >= count)
 83    return;
 84  if (y >= count)
 85    return;
 86
 87  Node *xp = get(*head, x - 1);
 88  Node *yp = get(*head, y - 1);
 89  Node *xc = get(*head, x);
 90  Node *yc = get(*head, y);
 91
 92  if (x == 0)
 93    *head = yc;
 94  else
 95    xp->next = yc;
 96
 97  if (y == 0)
 98    *head = xc;
 99  else
100    yp->next = xc;
101
102  Node *tmp = yc->next;
103  yc->next = xc->next;
104  xc->next = tmp;
105}
106
107/**
108 * A helper method used to print a visual representation
109 * of a linked list
110 *
111 * @param self The head of the linked list
112 */
113void inspect(Node *self) {
114  if (!self)
115    return;
116
117  printf("[");
118  while (self) {
119    printf(" %d ", self->data);
120    self = self->next;
121  }
122  printf("]\n");
123}