Skip to content

Instantly share code, notes, and snippets.

@saucecode
Created June 15, 2019 21:54
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 saucecode/1dfe86bc7f73b326de117e458aa54df0 to your computer and use it in GitHub Desktop.
Save saucecode/1dfe86bc7f73b326de117e458aa54df0 to your computer and use it in GitHub Desktop.
example linked lists implementation
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x;
int y;
float health;
} monster_t;
typedef struct {
void *next;
monster_t *monster;
} monster_list_t;
monster_list_t* list_create();
monster_list_t* list_append(monster_list_t *list, monster_t monster);
// Linked List Functions
monster_list_t* list_create() {
monster_list_t* list = (monster_list_t*) malloc(sizeof(monster_list_t));
list->monster = NULL;
list->next = NULL;
return list;
}
monster_list_t* list_append(monster_list_t *list, monster_t monster) {
while(list->next != NULL) list = list->next; // go to the last element
list->monster = (monster_t*) malloc(sizeof(monster_t));
*list->monster = monster;
list->next = list_create();
return list->next;
}
int main() {
monster_list_t *monsters = list_create();
// adding monsters to the list
for(int i=0; i<6; i++){
monster_t m = {rand()%20, rand()%20, 100.0f};
list_append(monsters, m);
}
// enumerating through a list
monster_list_t *head = monsters;
while(head->next != NULL) {
monster_t *monster = head->monster;
printf("Found a monster at %d, %d with %.1f health.\n", monster->x, monster->y, monster->health);
head = head->next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment