Created
January 16, 2015 19:43
-
-
Save ahirschberg/089e30b0bba5b9516ef7 to your computer and use it in GitHub Desktop.
Sam's C Linked List implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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