From 7e828ad441a6e894d3dc9a3cbb7d5aea0a16a970 Mon Sep 17 00:00:00 2001 From: orange Date: Tue, 2 Jul 2013 22:31:39 +0200 Subject: [PATCH] revert a list --- linked-list.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/linked-list.c b/linked-list.c index f923297..a6e18e2 100644 --- a/linked-list.c +++ b/linked-list.c @@ -81,9 +81,36 @@ void list_remove(list_t * list, list_node_t * item) { } } -/* FIXME - * list_node_t list_revert(list_node_t *list) { -} */ +void list_revert(list_t *list) { + list_t reverted; + reverted.head = NULL; + + list_node_t *cur = list->head; + while (cur != NULL) { + list_node_t *next = cur->next; + list_node_t *headbefore = reverted.head; + + reverted.head = cur; + cur->next = headbefore; + + cur = next; + } + + list->head = reverted.head; +} + +list_node_t* list_elementat(list_t *list, int i) { + if (i > list_length(list)-1) { + return NULL; + } + + list_node_t *cur = list->head; + for (int j=0; j < i; j++) { + cur = cur->next; + } + + return cur; +} int main(int argc, char *argv[]) { list_t *emptylist = malloc(sizeof(list_t)); @@ -167,4 +194,35 @@ int main(int argc, char *argv[]) { assert(list_empty(foolist) == true); list_print(foolist); printf("list_length = %d\n", list_length(foolist)); + + /* revert a list */ + const int howmany2 = 10; + for (int i = 0; i < howmany2; i++) { + list_node_t *newnode = malloc(sizeof(list_node_t)); + newnode->data = i; + + list_add(foolist, newnode); + } + + for (int i = 0; i < howmany2; i++) { + list_node_t *el = list_elementat(foolist, i); + assert(el->data == i); + } + + assert(list_length(foolist) == howmany2); + list_print(foolist); + printf("list_length = %d\n", list_length(foolist)); + + list_revert(foolist); + + for (int i = 0; i < howmany2; i++) { + list_node_t *el = list_elementat(foolist, i); + assert(el->data == howmany2-i-1); + } + + assert(list_length(foolist) == howmany2); + list_print(foolist); + printf("list_length = %d\n", list_length(foolist)); + + /* FIXME: frees */ }