Skip to content

Instantly share code, notes, and snippets.

@ahirschberg
Created January 16, 2015 19:43
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 ahirschberg/089e30b0bba5b9516ef7 to your computer and use it in GitHub Desktop.
Save ahirschberg/089e30b0bba5b9516ef7 to your computer and use it in GitHub Desktop.
Sam's C Linked List implementation
#include <stdlib.h>
#include <stdio.h>
struct listnode {
int head;
struct listnode *tail;
};
struct listnode *cons(int data, struct listnode *list) {
struct listnode *newlist = malloc(sizeof (struct listnode));
newlist->head = data;
newlist->tail = list;
return newlist;
}
struct listnode *cdr(struct listnode *list) {
return list->tail;
}
int car(struct listnode *list) {
return list->head;
}
void printlist(struct listnode *list) {
printf("%d ", car(list));
if (cdr(list)) {
printlist(cdr(list));
}
}
int main() {
struct listnode *list = NULL;
list = cons(1, list);
list = cons(2, list);
list = cons(3, list);
list = cons(6, cons(7, cons(8, list)));
printlist(list);
puts("");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment