diff --git a/src/list.c b/src/list.c index 634e12e..bcb9ca9 100644 --- a/src/list.c +++ b/src/list.c @@ -184,6 +184,26 @@ int List_sort(List *list, bool reverse) { return List_mergeSort(list, 0, list->_currentSize, reverse); } +int List_reverse(List *list) { + for (int i = 0, j = list->_currentSize; i < j; i++, j--) { + int element = List_get(list, j); + if (element == ERRNO_003) { + return element; + } + + int previousElement = List_insert(list, i, element); + if (previousElement == ERRNO_003) { + return element; + } + + if (List_insert(list, j, previousElement) == ERRNO_003) { + return ERRNO_003; + } + } + + return 0; +} + List *List_copy(List *list) { List *listCopy = List_createList(list->_maxSize, list->_currentSize); if (!listCopy) { diff --git a/src/list.h b/src/list.h index db0e272..4df70ab 100644 --- a/src/list.h +++ b/src/list.h @@ -120,6 +120,25 @@ int List_remove(List *list, int element); */ int List_sort(List *list, bool reverse); +/* + * + * Description + * ---------------------------- + * Reverse the elements in the list + * ======================================= + * WARNING: This is an in-place operation + * ======================================= + * + * Params + * ---------------------------- + * *list the list to reverse elements in + * + * Returns + * ---------------------------- + * int (0 for success, Non-0 for error) + */ +int List_reverse(List *list); + /* * * Description diff --git a/src/test/test.c b/src/test/test.c index 4e57988..a7b1545 100644 --- a/src/test/test.c +++ b/src/test/test.c @@ -159,6 +159,26 @@ void shouldRemoveElementFromList() { printSuccess(__func__); } +void shouldReverseList() { + // Arrange + List *list = List_new(); + List_append_all(list, 5, 50, 100, 75, 200, 300); + + // Act + int returnCode = List_reverse(list); + + // Assert + assert(returnCode == 0); + assert(List_get(list, 0) == 300); + assert(List_get(list, 1) == 200); + assert(List_get(list, 2) == 75); + assert(List_get(list, 3) == 100); + assert(List_get(list, 4) == 50); + List_destroy(&list); + + printSuccess(__func__); +} + int main() { printf("============================================"); printf("\nSTART TESTING"); @@ -172,6 +192,7 @@ int main() { shouldCopyEmptyList(); shouldInsertElementIntoListIndexZero(); shouldRemoveElementFromList(); + shouldReverseList(); printf("\n\n============================================"); printf("\nFINISH TESTING"); printf("\n============================================");