string reversal using stack【1月19日学习笔记】

点击查看代码
//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;
}
posted @ 2024-01-19 19:18  bituion  阅读(16)  评论(0)    收藏  举报