-
-
Save n2iw/c94ca78d61af19d434c7 to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <string.h> | |
//1.2 Implement a function void reverse(char* str) in C or C++ | |
// which reverses a null terminated string. | |
//O(N) time, O(1) space | |
void reverse(char* str) { | |
if (str == NULL) { | |
return; | |
} | |
unsigned long length = strlen(str); | |
/* here is what starlen does | |
while (*(str + length)) { | |
++length; | |
} | |
*/ | |
char *head = str; | |
char *tail = str + length -1; | |
while ( tail - head > 0 ) { //will handle even and odd and 0 length situation | |
char temp = *head; | |
*head = *tail; | |
*tail = temp; | |
++head; | |
--tail; | |
} | |
} | |
int main() { | |
char t1[100]; //can't use string literal here, because you can't modify it | |
//otherwise you'll get "Bus error 10" error, ask me how I know! | |
reverse(NULL); | |
strcpy(t1, ""); | |
printf("before:\"%s\"\n", t1); | |
reverse(t1); | |
printf("after:\"%s\"\n", t1); | |
strcpy(t1, "a"); | |
printf("before:\"%s\"\n", t1); | |
reverse(t1); | |
printf("after:\"%s\"\n", t1); | |
strcpy(t1, "ab"); | |
printf("before:\"%s\"\n", t1); | |
reverse(t1); | |
printf("after:\"%s\"\n", t1); | |
strcpy(t1, "abc"); | |
printf("before:\"%s\"\n", t1); | |
reverse(t1); | |
printf("after:\"%s\"\n", t1); | |
strcpy(t1, "abcd"); | |
printf("before:\"%s\"\n", t1); | |
reverse(t1); | |
printf("after:\"%s\"\n", t1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment