如何从第一个到最后一个打印Stack元素



这将向堆栈添加5个数字,并以反向打印它们

输入:1 2 3 4 5

输出:5 4 3 2 1

如何从1-5开始打印?

#include <iostream>
#include <stack>
using namespace std;
void print(stack <int> s)
{
while (!s.empty())
{
cout << " " << s.top();
s.pop();
}
cout << endl;
}
int main(){
stack <int> s;
int n;
for (int i = 0; i < 5; i++)
{
cin >> n;
s.push(n);
}
print(s);
}

您的赋值希望您反转堆栈。你可以在互联网上搜索"c++中的反向堆栈",找到许多解决方案。

void print(stack<int> s)的简单而粗的溶液如下所示:

void print(stack<int> s){
stack<int> temp;
while(!s.empty()){
temp.push(s.top());
s.pop();
}
while(!temp.empty()){
cout<<" "<<temp.top();
temp.pop();
}
cout<<endl;
}

这个解决方案背后的算法非常简单。它创建一个临时堆栈,并将堆栈s中的每个元素推入其中。现在它迭代并打印所有元素。

可以在互联网上找到更优化、写得更好的代码。

最新更新