点击查看代码
//string reversal using stack
#include<iostream>
#include<stack>//stack from standard template library(STL)
using namespace std;
void reverse(char *c,int n) {
stack<char> S;
for (int i = 0; i < n; i++) {
S.push(c[i]);//stack operation needs constant time
}
for (int i = 0; i < n; i++) {
c[i] = S.top();
S.pop();
}
}//时间复杂度:O(n)
//空间复杂度:O(n)//extra space
/*空间复杂度O(1)的算法:
int i=start, j=end;
while (i < j) {
swap(c[i], c[j]);
i++;
j--;
}
*/
int main() {
char c[51];
cin >> c;
reverse(c, strlen(c));
cout << c;
}