栈的实现比较简单一点,主要是考虑先进后出就可以了。
#ifndef _STACK_
#define _STACK_
#include <iostream>
using namespace std;
template <typename T>
class Node{
public: T m_data;
Node<T> *next;
Node(const T data) : m_data(data),next(NULL){}
Node(void) { next=NULL; }
~Node(){}
bool operator >(Node<T> it){
if (this->m_data > it.m_data)
return true;
else
return false;
}
};
template <typename T>
class myStack{
private:
int m_count;
Node<T> *m_top;
public:
myStack():m_count(0),m_top(NULL){}
~myStack(){}
T getTop();
void Push(T e);
T Pop();
bool isEmpty();
void clear();
void Print();
};
#endif
template <typename T>
T myStack<T>::getTop()
{
if (NULL!=m_top)
{
return m_top->m_data;
}
}
template <typename T>
void myStack<T>::Push( T e )
{
Node<T> *tmp=new Node<T>;
tmp->m_data=e;
tmp->next=m_top;
m_top=tmp;
}
template <typename T>
T myStack<T>::Pop()
{
if (NULL!=m_top)
{
T e=m_top->m_data;
Node<T> *tmp=m_top;
m_top=tmp->next;
tmp->next=NULL;
delete tmp;
return e;
}
}
template <typename T>
bool myStack<T>::isEmpty()
{
return NULL==m_top;
}
template <typename T>
void myStack<T>::clear()
{
Node<T> *tmp=m_top;
while(m_top){
m_top=tmp->next;
tmp->next=NULL;
delete tmp;
tmp=m_top;
}
}
template <typename T>
void myStack<T>::Print()
{
Node<T> *tmp=m_top;
while (NULL!=tmp)
{
cout<<tmp->m_data<<"\t";
tmp=tmp->next;
}
cout<<endl;
}
void main()
{
myStack<int> *stk=new myStack<int>();
stk->Push(9);
stk->Push(32);
stk->Push(23);
stk->Print();
int m=stk->Pop();
cout<<"After pop:";
stk->Print();
bool flag=stk->isEmpty();
cout<<flag;
stk->clear();
stk->Print();
getchar();
return;
}