#include <iostream>
#include <string.h>
using namespace std;
template<class T>
class STACK{
private:
struct Node{
T val;
struct Node *next;
};
Node *top;
int empty;
public:
STACK();
void push(T x);
void pop();
T gettop();
void print();
int is_empty();
};
template<class T>
STACK<T>::STACK()
{
top==NULL;
empty=0;
}
template<class T>
void STACK<T>::push(T x)
{
Node *p;
p=new Node;
if(p==NULL){
cout<<"内存不足!"<<endl;
exit(1);
}
p->val=x;
p->next=top;
top=p;
}
template<class T>
void STACK<T>::pop()
{
Node *p;
if(top==NULL)
{
cout<<"栈为空!"<<endl;
exit(1);
}
p=top;
top=top->next;
delete p;
}
template<class T>
T STACK<T>::gettop()
{
T x;
if(top==NULL)
{
cout<<"栈为空!"<<endl;
exit(1);
}
x=top->val;
return x;
}
template<class T>
void STACK<T>::print()
{
Node *p;
p=top;
if(p==NULL)
{
cout<<"栈为空!"<<endl;
exit(1);
}
cout<<"栈中元素为:";
while(p!=NULL)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
}
template<class T>
int STACK<T>::is_empty()
{
return (top==NULL)?0:1;
}
int main()
{
STACK<int>int_stack;
int i;
for(i=1;i<=10;i++)
int_stack.push(i);
// int_stack.print();
int_stack.pop();
cout<<"栈顶元素为:"<<int_stack.gettop()<<endl;
STACK<char *>str_stack;
str_stack.push("aajhjaas");
str_stack.push("csaaa");
// str_stack.print();
cout<<"栈顶元素为:"<<str_stack.gettop()<<endl;
str_stack.pop();
cout<<"栈顶元素为:"<<str_stack.gettop()<<endl;
}