From f6ef53c59e0f3700b4820aa1cfaad58922e0822b Mon Sep 17 00:00:00 2001 From: neingeist Date: Fri, 10 May 2013 14:32:21 +0200 Subject: [PATCH] add trivial linked list example --- Makefile | 7 +++++-- linked-list.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 linked-list.c diff --git a/Makefile b/Makefile index 1e5aae3..5a112a3 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,10 @@ -CFLAGS=-std=c99 +CFLAGS=-std=c99 -Wall -g INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2 -all: approximate-pi +all: approximate-pi linked-list + +clean: + rm -f approximate-pi linked-list .PHONY: indent indent: diff --git a/linked-list.c b/linked-list.c new file mode 100644 index 0000000..6097910 --- /dev/null +++ b/linked-list.c @@ -0,0 +1,44 @@ +#include +#include "assert.h" + +struct list_node { + int data; + struct list_node *next; +}; +typedef struct list_node list_node_t; + +int list_length(list_node_t * list) { + list_node_t *cur; + int count = 0; + + cur = list; + while (cur != NULL) { + count++; + cur = cur->next; + } + + return count; +} + +void list_print(list_node_t * list) { + list_node_t *cur; + + cur = list; + while (cur != NULL) { + printf("%d ", cur->data); + cur = cur->next; + } + printf("\n"); +} + +int main(int argc, char *argv[]) { + list_node_t *emptylist = NULL; + assert(list_length(emptylist) == 0); + list_print(emptylist); + printf("list_length = %d\n", list_length(emptylist)); + + list_node_t foo = { 1, NULL }; + assert(list_length(&foo) == 1); + list_print(&foo); + printf("list_length = %d\n", list_length(&foo)); +}