Skip to content

Instantly share code, notes, and snippets.

@ods94065
Created March 16, 2013 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ods94065/5178095 to your computer and use it in GitHub Desktop.
Save ods94065/5178095 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Person {
char name[16];
char text[24];
};
struct Node {
void* data;
struct Node* next;
};
struct List {
struct Node* head;
};
struct Person* person_new(char* name, char* text)
{
struct Person* p = (struct Person*) malloc(sizeof(struct Person));
strncpy(p->name, name, 15);
p->name[15] = '\0';
strncpy(p->text, text, 23);
p->name[23] = '\0';
return p;
}
struct Node* node_new(void* data)
{
struct Node* n = (struct Node*) malloc(sizeof(struct Node));
n->data = data;
n->next = NULL;
return n;
}
struct List* list_append(struct List* lis, void* data)
{
struct Node* new_node = node_new(data);
struct Node* n = lis->head;
if (! n) {
lis->head = new_node;
} else {
while (n->next) {
n = n->next;
}
n->next = new_node;
}
return lis;
}
void traverse(struct List* a, void (*f)(void*))
{
struct Node* n = a->head;
while (n) {
f(n->data);
n = n->next;
}
}
static void print(void* data) {
struct Person* p = (struct Person*) data;
printf("%s\n", p->name);
}
int main(int argc, char** argv)
{
/* create a sample two-item list and test it */
struct List ps;
struct Person* p;
struct Person* p2;
p = person_new("Jack", "");
list_append(&ps, p);
p2 = person_new("Jill", "");
list_append(&ps, p2);
traverse(&ps, &print);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment