Add List_reverse()

main
Hammy 3 years ago
parent ce668465e7
commit 1841d34ed8

@ -184,6 +184,26 @@ int List_sort(List *list, bool reverse) {
return List_mergeSort(list, 0, list->_currentSize, 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 *List_copy(List *list) {
List *listCopy = List_createList(list->_maxSize, list->_currentSize); List *listCopy = List_createList(list->_maxSize, list->_currentSize);
if (!listCopy) { if (!listCopy) {

@ -120,6 +120,25 @@ int List_remove(List *list, int element);
*/ */
int List_sort(List *list, bool reverse); 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 * Description

@ -159,6 +159,26 @@ void shouldRemoveElementFromList() {
printSuccess(__func__); 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() { int main() {
printf("============================================"); printf("============================================");
printf("\nSTART TESTING"); printf("\nSTART TESTING");
@ -172,6 +192,7 @@ int main() {
shouldCopyEmptyList(); shouldCopyEmptyList();
shouldInsertElementIntoListIndexZero(); shouldInsertElementIntoListIndexZero();
shouldRemoveElementFromList(); shouldRemoveElementFromList();
shouldReverseList();
printf("\n\n============================================"); printf("\n\n============================================");
printf("\nFINISH TESTING"); printf("\nFINISH TESTING");
printf("\n============================================"); printf("\n============================================");

Loading…
Cancel
Save