64,685
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
template<class Type>
class Stack{
int stacksize;
Type *items;
int top;
public:
explicit Stack(int ss);
Stack(const Stack &st);
~Stack(){delete [] items;}
void push(const Type &item);
Type pop();
Stack &operator=(const Stack &st);
};
template <class Type>
inline Stack<Type>::Stack(int ss=0):
stacksize(ss),top(0){
items=new Type[stacksize];
}
template <class Type>
Stack<Type>::Stack(const Stack &st){
stacksize=st.stacksize;
top=st.top;
items=new Type [stacksize];
for(int i=0;i<top;i++){
items[i]=st.items[i];
}
}
template <class Type>
inline void Stack<Type>::push(const Type& item){
if(top<stacksize)
items[top++]=item;
else
cout<<"the stack is full"<<endl;
}
template <class Type>
inline Type Stack<Type>::pop(){
if(top>0)
return items[top--];
else
cout<<"the stack is empty!"<<endl;
}
template <class Type>
inline Stack<Type> &Stack<Type>::operator =(const Stack<Type> &st){
if(this==&st)
return *this;
delete [] items;
stacksize=st.stacksize;
top=st.top;
items=new Type [stacksize];
for(int i=0;i<top;i++)
items[i]=st.items[i];
return *this;
}
int main()
{
int m;char *str;
cout<<"enter stack size:"<<endl;
cin>>m;
if(m<=0)
cout<<"error of size"<<endl;
else
{
Stack<char> st(20);
str=new char[m];
cin>>str;
for(int i=0;i<m;i++){
st.push(str[i]);
}
for(int j=0;j<m;j++){
cout<<st.pop()<<endl;
}
cout<<endl;
delete [] str;
}
return 0;
}