题目:
给定一个字符串, 该字符串由英文单词构成, 该函数的作用是把这个字符串中的单词逆序排列, 比如输入字符串为"This is a dog", 那么运行该函数后该字符串应转化为"dog a is This"
算法: 逆序所有字符串,然后再逆序所有单词, 两者顺序无所谓!
char* Reverse(char* start, char* end)
{
if (start == NULL || *start == '\0' || end == NULL || *end == '\0')
return NULL;
char* p = start; // 首地址
char ch;
while(start < end)
{
ch = *start;
*start++ = *end;
*end-- = ch;
}
return p;
}
char* ReverseEveryWord(char* p)
{
if (p == NULL || *p == '\0')
return NULL;
char* left= p;
char* right = p;
while(*right)
{
if (*right == ' ' || *right == '\0')
{
Reverse(left,right-1);
left = right+1;
}
right++;
}
// Revere last word
Reverse(left, right-1);
return p;
}
char* ReverseWholeString(char* p)
{
if (p == NULL || *p == '\0')
return NULL;
char* start = p;
while(*p++)
;
p -= 2; // 最后一个字符的地址
return Reverse(start, p);
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[] = "This is a dog";
ReverseWholeString(str);
ReverseEveryWord(str);
return 0;
}