Created
June 16, 2014 03:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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