Skip to content

Instantly share code, notes, and snippets.

@davissp14
Created December 21, 2012 05:19
Show Gist options
  • Save davissp14/4350819 to your computer and use it in GitHub Desktop.
Save davissp14/4350819 to your computer and use it in GitHub Desktop.
Basic implementation of a linked list in C.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct person {
char *name;
struct person *next;
} person;
void display(person *start) {
person *i = start;
for(; i != NULL; i = i->next){
printf("Name: %s\n", i->name);
}
};
void release(person *start) {
person *i = start;
person *next = NULL;
for(; i != NULL; i = next){
next = i->next;
free(i->name); /* free strdup */
free(i); /* free person from heap */
}
}
person* create(char *name) {
person *i = malloc(sizeof(person)); /* Add person to heap */
i->name = strdup(name); /* dup string and place on heap */
i->next = NULL;
return i;
};
int main()
{
person *next = NULL;
person *i = NULL;
person *start = NULL;
char name[80];
for(; fgets(name, 80, stdin) != NULL; i = next ) {
if ((int)strlen(name) == 1) /* In this case \n is treated as null */
break;
next = create(name);
if (start == NULL)
start = next;
if (i != NULL)
i->next = next;
}
display(start);
release(start);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment