Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created April 9, 2018 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/f8f426b2d6db4f463ebfb5300801fec0 to your computer and use it in GitHub Desktop.
Save JoshCheek/f8f426b2d6db4f463ebfb5300801fec0 to your computer and use it in GitHub Desktop.
Data Structures: First parts of a linked list in C
#include <stdio.h>
#include <stdlib.h>
// (4, head) <-- base of the list
// /
// / ("c") -> ("d") -> ("e")
// ("b")----/
struct node {
char* data;
struct node* next;
};
typedef
struct node
Node;
struct base {
int count;
Node* head;
};
typedef
struct base
List;
List* list_create() {
List* list = malloc(sizeof(List));
(*list).count = 0;
(*list).head = NULL;
return list;
}
void list_add(char* string, List* list) {
Node* new_node = malloc(sizeof(Node));
(*new_node).data = string;
(*new_node).next = (*list).head;
(*list).head = new_node;
(*list).count += 1;
}
void list_print(char* description, List* list) {
printf("=== %s ===\n", description);
printf("%d items:\n", list->count);
Node* element = list->head;
while(element) {
printf("\"%s\"", (*element).data);
element = (*element).next;
if(element)
printf("->");
}
printf("\n\n");
}
int main(int argc, char** argv) {
List* list = list_create();
list_print("initial", list);
list_add("e", list);
list_print("with e", list);
list_add("d", list);
list_print("with d", list);
list_add("c", list);
list_print("with c", list);
list_add("b", list);
list_print("with b", list);
// FREE THE MEMS, YO!!
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment