如题:规则如下
方法1:借助辅助的空间
输入:im a bad student
输出:student bad a im
方法1:不借助辅助的空间
#include <iostream>
#include <algorithm>
using namespace std;
void ReverseWord(char a[], int begin, int end)
{
for(; begin < end; ++begin, --end)
swap(a[begin], a[end - 1]);
}
void Reverse(char str[])
{
int front = 0;
int cur = 0;
for(; str[cur] != '\0'; ++cur)
if(str[cur] == ' ')
{
ReverseWord(str, front, cur);
front = cur + 1;
}
ReverseWord(str, front, cur);
}
int main()
{
//char s[] = "im a bad boy";
char s[] = "im a bad student";
int len = strlen(s);
ReverseWord(s, 0, len);
Reverse(s);
cout<< s <<endl;
return 0;
}
方法1:借助辅助的空间
#include <iostream>
#include <stack>
#include <string.h>
#include <algorithm>
using namespace std;
void PushStack(char s[], stack<string> &stk)
{
const char *tag = " ";
char *p = strtok(s, tag);
while(p)
{
stk.push(p);
p = strtok(NULL, tag);
}
}
int main()
{
stack<string> stk;
char s[] = "im a bad student";
PushStack(s, stk);
//输出
while(!stk.empty())
{
cout<< stk.top() << " ";
stk.pop();
}
return 0;
}