- #include <iostream>
- #include <stack>
- #include <vector>
- #include <deque>
- using namespace std;
- //利用堆栈实现反转
- char *reverseByStack(char *string)
- {
- stack<char> sent;
- char *addr,*p;
- addr=p=string;
- while (*p!='\\0')
- sent.push(*p++); //push sentence into stack;
- while (true)
- {
- bool end=false;
- stack<char> word;
- while (sent.top()!=' ')
- {
- word.push(sent.top());
- sent.pop();
- if (sent.empty())
- {
- end=true;
- break;
- }
- }
- if (word.empty())
- {
- *string++=' ';
- sent.pop();
- if (sent.empty())
- break;
- continue;
- }
- else
- {
- while(!word.empty())
- {
- *string++=word.top();
- word.pop();
- }
- if (end)
- break;
- }
- }
- return addr;
- }
- void swap(char *s,char *e)
- {
- while(s<e)
- {
- char temp=*s;
- *s=*e;
- *e=temp;
- s++;
- e--;
- }
- }
- //利用普通方法实现反转
- char *reverseString(char *string)
- {
- char *beg = string;
- char *end = beg+strlen(string)-1;
- //1.total reverse
- swap(beg,end);
- //2.word reverse
- while (*beg!='\\0')
- {
- if (*beg==' ')
- {
- beg++;
- continue;
- }
- end=beg;
- while(*end!=' '&&*end!='\\0')
- end++;
- swap(beg,--end);
- beg=++end;
- }
- return string;
- }
- int main()
- {
- char string[25]="Who are you girl?";
- char string2[25]="Who are you girl?";
- cout<<"Before Reverse:"<<endl;
- cout<<string<<endl;
- cout<<"After (common method) Reverse:"<<endl;
- cout<<reverseString(string)<<endl;
- cout<<"After (stack method) Reverse:"<<endl;
- cout<<reverseByStack(string2)<<endl;
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/250920136119.html
来源: http://www.codesnippet.cn/detail/250920136119.html