学C++ 的时候写的模板类以作为对C++的练习,
#include <stdlib.h>
#include <malloc.h>
#define stack_init_size 100
template<class T>
class CStack
{
public:
CStack(void);
~CStack(void);
public:
// ------------栈的顺序存储表示--------------
static struct _tagStack
{
T* base; //在栈构造之前和销毁之后,base 的值为null;
T* top; //栈顶指针
int stacksize;
};
private:
typedef _tagStack SqStack;
public:
int Push(SqStack& S, T e);
int InitStack(SqStack& s);
int Pop(SqStack& s, T& e);
int StackEmpty(SqStack s);
int StackLength(SqStack s);
void GetTop(SqStack s,T& e);
void ClearStack(SqStack& s);
void DestroyStack(SqStack& s);
void StackTraverse(SqStack& s);
//迷宫求解 经典算法
// int MazePath(MazeType maze,PostType start,PostType end);
};
template<class T>
CStack<T>::CStack(void)
{
}
template<class T>
CStack<T>::~CStack(void)
{
}
//入栈
template<class T>
int CStack<T>::Push(SqStack& S, T e)
{
if(S.top - S.base >= S.stacksize) //栈满,追加存储
{
S.base = (T*) realloc(S.base,
(S.stacksize + stack_init_size) * sizeof(T));
if(S.base == NULL) return -1;
S.top = S.base + S.stacksize;
S.stacksize += stack_init_size;
}
*S.top++ = e;
return 0;
}
//初始化栈
template<class T>
int CStack<T>::InitStack(SqStack& s)
{
s.base = new T[stack_init_size];
if(s.base == NULL) return -1;
s.top = s.base;
s.stacksize = stack_init_size;
return 0;
}
//弹出栈顶
template<class T>
int CStack<T>::Pop(SqStack& s, T& e)
{
if(s.top == s.base) //栈已空
{
return -1;
}
e = *--s.top;
return 0;
}
//判断栈是否为空
template<class T>
int CStack<T>::StackEmpty(SqStack s)
{
if(s.base == s.top) return 1;
return 0;
}
//清空栈
template<class T>
void CStack<T>::ClearStack(SqStack& s)
{
T* tmp = s.base;
while(tmp!= s.top)
*tmp =NULL;
}
//返回栈顶数据
template<class T>
void CStack<T>::GetTop(SqStack s,T& e)
{
if(s.top == s.base ) //栈为空
return;
e = *(s.top-1);
}
//取得栈的长度
template<class T>
int CStack<T>::StackLength(SqStack s)
{
return (s.top-s.base);
}
//销毁栈
template<class T>
void CStack<T>::DestroyStack(SqStack& s)
{
s.top = s.base;
}
template<class T>
void CStack<T>::StackTraverse(SqStack& s)
{
int i=0;
T tmp;
int len=StackLength(s);
for(;i<len/2;i++)
{
tmp = *(s.base + i);
*(s.base + i) = *(s.base + len - i - 1);
*(s.base + (s.top - s.base) - i - 1) = tmp;
}
}
/*
***********************************************************************
TEST
***********************************************************************
*/
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"/nStack:-----------------------/n";
CStack<char*> stack;
CStack<char*>::_tagStack s;
stack.InitStack(s);
stack.Push(s,"12");
stack.Push(s,"24");
stack.Push(s,"23");
stack.Push(s,"43");
stack.Push(s,"565");
stack.Push(s,"36");
stack.Push(s,"432");
char* tmp="";
while(!stack.StackEmpty(s))
{
stack.Pop(s,tmp);
cout<<tmp<<endl;
}
cout<<"length"<<stack.StackLength(s)<<endl;
stack.Push(s,"12");
stack.Push(s,"24");
stack.Push(s,"23");
stack.Push(s,"43");
stack.Push(s,"565");
stack.Push(s,"36");
stack.Push(s,"432");
stack.StackTraverse(s);
while(!stack.StackEmpty(s))
{
stack.Pop(s,tmp);
cout<<tmp<<endl;
}
stack.DestroyStack(s);
}