11-recursion-algos/reverse_string.c

47 lines
No EOL
1.4 KiB
C

/*----------------------------------------------------------
* HTBLA-Leonding / Class: <your class>
* ---------------------------------------------------------
* Title: Reverse String
* Author: Marc Tismonar
* ----------------------------------------------------------
* Description:
* Recursive and iterative implementation of an algorithm that
* reverses a given string.
* ----------------------------------------------------------
*/
#include "reverse_string.h"
/*
Instructions:
Define a function reverse_string(s) that takes a string `s` as input.
Take the last character of `s` and concatenate it with the result of reversing the rest of the string until the string has less than two characters.
Note that strings that are stored on heap or stack are provided - they can be directly manipulated.
*/
// TODO: the recursive implementation
void reverse_string_recursive(char* str, int start, int end) {
if(start >= end) {
return;
}
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
reverse_string_recursive(str, start, end);
}
void reverse_string_iterative(char* str, int start, int end) {
while(start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}