栈(C++模板类实现)

 - by Hector

[CODE=cplusplus]
/*//////////////////////////////////////////////////////////////////////////////

// 名 称 (Unit Name): Stack.h 头文件

// 作 者 (Author ): Hector(张伟)

// 邮 箱 (E-mail ): ourys@qq.com

// 支 持 (Support ): http://www.ourys.com

// 备 注 (Remarks ):

//////////////////////////////////////////////////////////////////////////////*/

#ifndef _STACK_H

#define _STACK_H

#define STACK_INIT_SIZE 100 //初始的最大长度

#define STACKINCREMENT 10 //每次新增的栈的长度

template

class Stack{

public:

Stack();

void Push(DataType e); //插入为e的新栈顶元素

int Pop(DataType &e); //删除栈顶元素

int GetTop(DataType &e); //取出栈顶元素

int StackEmpty(); //判断栈是否为空:空返回1

~Stack(); //栈被销毁

private:

DataType *base; //栈尾

DataType *top; //栈顶

int stacksize;

};

/*———— 构造函数,创建一个新的空栈 ————–*/

template

Stack::Stack()

{

if(!(base=(DataType*)malloc(STACK_INIT_SIZE*sizeof(DataType)))) exit(1);

top=base;

stacksize=STACK_INIT_SIZE;

}

/*——– 插入为e的新栈顶元素 ————–*/

template

void Stack::Push(DataType e)

{

if(top-base>=stacksize){

if(!(base=(DataType*)realloc(base,(stacksize+STACKINCREMENT)*sizeof(DataType)))) exit(1);

top=base+stacksize;

stacksize+=STACKINCREMENT;

}

*top++=e;

}

/*——– 删除栈顶元素 ————–*/

template

int Stack::Pop(DataType &e)

{

if(top==base) return 0;

e=*–top;

return 1;

}

/*——– 取出栈顶元素 ————–*/

template

int Stack::GetTop(DataType &e)

{

if(top==base) return 0;

e=*(top-1);

return 1;

}

/*———— 判断栈是否为空:空返回1 ————–*/

template

int Stack::StackEmpty()

{

return top==base? 1:0;

}

/*———— 销毁栈 ————–*/

template

Stack::~Stack()

{

free(base);

}

#endif



/*//////////////////////////////////////////////////////////////////////////////

// 名 称 (Unit Name): main.cpp 栈头基本测试文件

// 作 者 (Author ): Hector(张伟)

// 邮 箱 (E-mail ): ourys@qq.com

// 支 持 (Support ): http://ourys.com

// 备 注 (Remarks ):

//////////////////////////////////////////////////////////////////////////////*/

#include

using namespace std;

#include “Stack.h”

int main()

{

Stack my;

int a;

for(int i=0;i<12;i++) my.Push(i);

for(int i=0;i<12;i++)

{

my.Pop(a);

cout<
}

return 0;

}
[/CODE]

Leave a comment