//stl实现,引用stack库
#include<iostream>
#include<stack>
using namespace std;
stack<int>A;
int main()
{
int x,op;
//1输入元素
//2弹出栈顶元素
// 弹出栈顶
for(;;)
{
scanf("%d",&op);
if(op==1){
scanf("%d",&x);
A.push(x);
}else if(op==2){
cout<<A.top()<<endl;
A.pop();
}else
printf("Input Error");
}
return 0;
}
//利用数组手写栈
#include<iostream>
#include<cstdio>
using namespace std;
int A[100];
int main()
{
int x,op,tot=0;
//1输入元素
//2弹出栈顶元素
// 弹出栈顶
for(;;)
{
scanf("%d",&op);
if(op==1){
scanf("%d",&x);
A[++tot] = x;
}else if(op==2)
cout<<A[tot--]<<endl;
else
printf("Input Error");
}
return 0;
}
本文介绍了使用C++ STL库中的stack容器实现栈的基本操作,包括元素的压入和弹出,并展示了如何通过数组手动实现栈的数据结构。两种实现方式均提供了代码示例,便于理解和实践。
2364

被折叠的 条评论
为什么被折叠?



