//=====================Stack.h=================
#include<iostream>
using namespace std;
template<typename DataType> class Stack
{
public:
Stack(int size)
{
maxSize=size;
top=-1;
elements=new DataType[size];
}
~Stack()
{
delete [] elements;
}
//入栈操作
bool push(DataType data);
//出栈
DataType pop();
private:
DataType *elements;
int top;//栈顶序号
int maxSize;栈空间
};
template<typename DataType>bool Stack<DataType>::push(DataType data)
{
if(top==maxSize)
return false;
elements[++top]=data;
return true;
}
template<typename DataType> DataType Stack<DataType>::pop()
{
if(top==-1)
{
exit(1);
}
return elements[top--];
}
//=======================Stack.cpp==================
#include<iostream>
#include"stack.h"
using namespace std;
/*
int main()
{
Stack<int> s=Stack<int>(6);
int temp=0;
s.push(23);
s.push(56);
s.push(11);
temp=s.pop();
cout<<temp<<" ";
s.push(4);
temp=s.pop();
cout<<temp<<" ";
temp=s.pop();
cout<<temp<<" ";
s.push(86);
s.push(98);
temp=s.pop();
cout<<temp<<" ";
temp=s.pop();
cout<<temp<<" ";
temp=s.pop();
cout<<temp<<" ";
return 0;
}
*/
int main()
{
int size;
printf("请输入栈的大小:\n");
scanf("%d",&size);
Stack<int> ss=Stack<int>(size);
int temp;
printf("请输入栈元素:\n");
for(int i=0;i<size;i++)
{
int a;
scanf("%d",&a);
ss.push(a);
}
for(i=0;i<size;i++)
{
temp=ss.pop();
cout<<temp<<endl;
}
return 0;
}
//栈的特点是先进后出主要有两个操作入栈和出栈。都是在栈顶进行操作。