Stack类实现。模板

// Head.h
#include <iostream>
using namespace std;

#ifndef DEFAULT_STACK_SIZE
#define DEFAULT_STACK_SIZE 1000
#endif

// end 
// iCoding@CodeLab
//

 

 

 

// Stack.h
#include "Head.h"


template <typename ElemType>
class Stack
{
	private:
		ElemType *data;
		int size;
		int bottom;
		int top;
	public:
		Stack ();
		void push (ElemType elem);
		ElemType pop ();
		bool is_empty ();
		bool is_full ();
		int get_size ();
		void expand_size ();
};


// end 
// iCoding@CodeLab
//

 

#include "Stack.h"

///
// Stack
template <typename ElemType>
Stack<ElemType>::Stack ()
{
	this->size   = DEFAULT_STACK_SIZE;
	this->data   = new ElemType[this->size+1];
	this->bottom = 0;
	this->top    = 0;
}

///
// push 
template <typename ElemType>
void Stack<ElemType>::push (ElemType elem)
{
	if (is_full())
	{
		expand_size ();
	}
	this->top++;
	this->data[this->top] = elem;
}
///
// pop
template <typename ElemType>
ElemType Stack<ElemType>::pop ()
{
	ElemType elem_top;
	elem_top = this->data[this->top];
	this->top--;
	return elem_top;
}
///
// is empty
template <typename ElemType>
bool Stack<ElemType>::is_empty ()
{
	return (this->bottom >= this->top);
}

///
// is full
template <typename ElemType>
bool Stack<ElemType>::is_full ()
{
	return (this->size <= this->top);
}

///
// get size of Stack
template <typename ElemType>
int Stack<ElemType>::get_size ()
{
	return (this->top - this->bottom);
}

///
// expand_size
template <typename ElemType> 
void Stack<ElemType>::expand_size ()
{
	ElemType* elem_data_tmp;
	elem_data_tmp = new ElemType[this->size+1];
	for (int i = this->bottom + 1; i <= this->top; i++)
	{
		elem_data_tmp[i] = this->data[i];
	}
	delete[] this->data;
	this->size += DEFAULT_STACK_SIZE;
	this->data = new ElemType[this->size+1];
	for (int i = this->bottom + 1; i <= this->top; i++)
	{
		this->data[i] = elem_data_tmp[i];
	}
}

// end 
// iCoding@CodeLab
//

 

转载于:https://my.oschina.net/ism/blog/80785

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值