Refactored 'length(stack)' and added test.
This commit is contained in:
		
							parent
							
								
									b1000cfb55
								
							
						
					
					
						commit
						3420045a35
					
				
							
								
								
									
										12
									
								
								lib/stack.c
									
									
									
									
									
								
							
							
						
						
									
										12
									
								
								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); | ||||
|  | ||||
| @ -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(); | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user