qfedu-cpp-level/day9/homework/h4.cpp

43 lines
1.1 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 【场景】栈操作
// 编写一个程序演示栈stack的以下操作 1将一个元素压入栈顶。 2从栈顶弹出一个元素。 3获取栈顶元素的值。
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
void print(stack<T> &s)
{
cout << "当前栈中元素(按出栈顺序)打印如下: " << endl;
// 先将栈转存到另一个临时栈中,临时栈的元素顺序和原栈相反
// 临时栈用于打印,而不改变原栈的元素顺序
stack<T> tmp = s; // 拷贝原来的栈,避免改变原栈
while (!tmp.empty())
{
cout << tmp.top() << " ";
tmp.pop();
}
cout << endl;
cout << "------------------" << endl;
}
int main()
{
stack<int> stk;
stk.push(1);
stk.push(2);
stk.push(3);
stk.push(4);
stk.push(5);
print(stk);
cout << "从栈顶弹出一个元素: " << stk.top() << endl;
stk.pop();
print(stk);
cout << "获取栈顶元素的值: " << endl;
cout << stk.top() << endl;
return 0;
}