Skip to content

Instantly share code, notes, and snippets.

@ducc
Last active October 9, 2017 16:41
Show Gist options
  • Save ducc/b021c2f12d115385e3dbc88ff4bc04c1 to your computer and use it in GitHub Desktop.
Save ducc/b021c2f12d115385e3dbc88ff4bc04c1 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node * next;
} node_t;
node_t * node_new(void) {
node_t * new_node = NULL;
new_node = malloc(sizeof(node_t));
if (new_node == NULL) {
printf("could not allocate for node\n");
return NULL;
}
new_node->value = -1;
new_node->next = NULL;
return new_node;
}
node_t * list_new(void) {
node_t * head = node_new();
return head;
}
void list_add(node_t * list, int value) {
if (list->value == -1) {
list->value = value;
return;
}
node_t * new_node = node_new();
new_node->value = value;
// navigate to the last node
node_t * current_node = list;
if (current_node->next != NULL) {
while (current_node->next != NULL) {
current_node = current_node->next;
}
}
current_node->next = new_node;
}
void list_print(node_t * list) {
node_t * current_node = list;
while (current_node->next != NULL) {
printf("%d\n", current_node->value);
current_node = current_node->next;
}
printf("%d\n", current_node->value);
}
void list_cleanup(node_t * list) {
if (list == NULL) {
return;
}
list_cleanup(list->next);
free(list);
}
int main(void) {
node_t * list = list_new();
list_add(list, 5);
list_add(list, 95);
list_add(list, 134);
list_print(list);
list_cleanup(list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment