From 3420045a35ecd3ba1c8ca701a08c94cf08585c60 Mon Sep 17 00:00:00 2001 From: Murilo Pereira Date: Wed, 16 Feb 2011 22:42:49 -0200 Subject: [PATCH] Refactored 'length(stack)' and added test. --- lib/stack.c | 12 +++++------- test/stack_test.c | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/stack.c b/lib/stack.c index 12d2e63..b033f8d 100644 --- a/lib/stack.c +++ b/lib/stack.c @@ -45,15 +45,13 @@ bool empty(struct stack *stack) { } int length(struct stack *stack) { - struct stack *iterator = stack; - int length = 0; + int length; if (!empty(stack)) { - length = 1; - while (iterator->next != NULL) { - length++; - iterator = iterator->next; - } + for (length = 1; stack->next; stack = stack->next, length++) + ; + } else { + length = 0; } return(length); diff --git a/test/stack_test.c b/test/stack_test.c index 4a0bdcc..c4d5f9e 100644 --- a/test/stack_test.c +++ b/test/stack_test.c @@ -47,6 +47,28 @@ void test_empty_on_non_empty_stack() { return; } +void test_length() { + struct stack *stack; + struct card *card[4]; + + allocate_stack(&stack); + initialize_stack(stack); + + assert(length(stack) == 0); + + for (int i = 0; i < 4; i++) { + allocate_card(&card[i]); + initialize_card(card[i]); + set_card(card[i], i, SPADES, EXPOSED, 0, 0); + push(&stack, card[i]); + assert(length(stack) == i + 1); + } + + free_stack(stack); + + return; +} + void test_push_on_empty_stack() { struct stack *stack; struct card *card; @@ -199,6 +221,8 @@ void test_stack() { test_empty_on_empty_stack(); test_empty_on_non_empty_stack(); + test_length(); + test_push_on_empty_stack(); test_push_on_non_empty_stack(); test_push_null_on_empty_stack();