Skip to content

Instantly share code, notes, and snippets.

@n2iw

n2iw/cc150.1.2.c Secret

Last active August 29, 2015 14:18
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 n2iw/c94ca78d61af19d434c7 to your computer and use it in GitHub Desktop.
Save n2iw/c94ca78d61af19d434c7 to your computer and use it in GitHub Desktop.
#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