#include <iostream>
#include <stack>
#include<stdlib.h>
#include<string.h>
using namespace std;
char* _reverse(char *str)
{
stack<char> v1;
stack<char> v2;
//求字符串长度
int length = strlen(str);
char *temp = str;
//遍历字符串
for (int i = 0; i < length+1; i++)
{
//不为空,不为空格则压栈
if(temp[i] != ' ' && temp[i] != '\0')
v1.push(temp[i]);
//如果为空或者,空格
else{
//如果v1栈里有元素,则出栈,放入v2
while (v1.size())
{
char ch = v1.top();
v1.pop();
v2.push(ch);
}
//如果i没到末尾,则对v2压入一个空格
if (i < length-1)
v2.push(' ');
}
}
//把栈v2出栈到str
for (int i = 0; i < length; i++)
{
str[i] = v2.top();
v2.pop();
}
return str;
}
int main()
{
char str[] = "this is a pre job";
_reverse(str);
cout << str <<endl;
return 0;
}
总结:v1栈类似寻路,切割字符串。
v1会把字符串逆序,故v2的再次入栈则能将字符串的顺序回正