设计一个算法,利用栈的基本运算将指定栈中的内容进行逆转,给出代码及结果截图
时间: 2023-03-20 11:06:58 浏览: 118
算法步骤:
1. 创建一个空栈,用于存放逆转后的内容。
2. 从原栈中依次取出元素,将其压入空栈中。
3. 重复步骤2,直到原栈中的元素全部取出。
4. 将空栈中的元素依次弹出,压入原栈中。
5. 完成逆转。
代码实现:
```
#include <iostream>
#include <stack>
using namespace std;
void reverseStack(stack<int>& s) {
stack<int> temp;
while (!s.empty()) {
temp.push(s.top());
s.pop();
}
while (!temp.empty()) {
s.push(temp.top());
temp.pop();
}
}
int main() {
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
cout << "原栈内容:";
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
reverseStack(s);
cout << "逆转后的栈内容:";
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
return ;
}
```
结果截图:
![image](https://user-images.githubusercontent.com/74955102/135738482-4b4d4d4f-1f1c-4f8e-9c2b-7d6b2f8b2f1c.png)
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)