/* This is one of the solution set to CareerCup 150 problems.
*
* Problem 1.2
*
* Method 1: Swap the nth and the (count-n)th elements.
* Notice: Under gcc, char* can't be modified, we can only manipulate the char array.
* Method 2: Use stack, first in, last out.
*
* Date: 02/18/2013
* Compile command: gcc-4.7 1.2.c
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char str[]); //O(n) time, O(1) space
void reverseUseStack(char str[]); //O(n) time, O(n) space
int main(int argc, char *argv[])
{
char str[] = "1234abcd";
printf("Original string:\t%s\n",str);
//reverse(str);
reverseUseStack(str);
printf("Reversed string:\t%s\n",str);
return 0;
}
void reverse(char str[])
{
int len = strlen(str);
int i = 0;
int range = len - 1;
for(; range > 0; i++)
{
//loop 1:swap the first and the last element.
char tmp = str[i];
str[i] = str[i + range];
str[i + range] = tmp;
range -= 2;
}
}
void reverseUseStack(char str[])
{
int len = strlen(str);
char *strStack = malloc(len-1);
int index = 0;
for(len -= 1; len >=0; len--)
strStack[index++] = str[len];
strncpy(str, strStack, sizeof(str));
free(strStack);
strStack = NULL;
}
转载于:https://blog.51cto.com/hector/1140700