C++栈 push() top() pop()

//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;
}

猜你喜欢

转载自blog.csdn.net/luyi_c/article/details/88045540