Skip to content

Instantly share code, notes, and snippets.

@monkerek
Created June 16, 2014 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkerek/100587049a945115f589 to your computer and use it in GitHub Desktop.
Save monkerek/100587049a945115f589 to your computer and use it in GitHub Desktop.
CC1.2 Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
/* idea: using 2 pointers respectively point to the start and the end of the string,
swap the value they point to, then move the pointers iteratively.
time: complexity: O(n)
space complexity: O(1)
*/
void reverse(char* str)
{
if(!str)
return;
char *left = str, *right = str + strlen(str) - 1;
while(left < right)
{
swap(*left, *right); // built by stl, must include <algorithm>
left++;
right--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment