顺序表的头文件和头文件的实现

注意:1模板类中的函数有const,那么定义此函数时const必须要有

2定义模板类的函数时,template一定要有class

#ifndef _SQLIST_H_
#define _SQLIST_H_

#include 
using namespace std;
const DEFAULT_SIZE=10;
enum StatusCode{RANGE_ERROR,SUCCESS,NOT_PRESENT,ENTRY_FOUND,OVER_FLOW};
template
class SqList
{
protected:

	ElemType *ptr;
	int count;
	int maxSize;
	
	
	void init(int size);
	bool full()const;
	
public:
	SqList(int size=DEFAULT_SIZE);
	virtual ~SqList();
	int length()const;
	bool isEmpty()const;
	void clear();

	StatusCode setElem(int position,const ElemType &e);
	StatusCode getElem(int position,ElemType &e)const;
	StatusCode Insert(int position,const ElemType &e);
	StatusCode Delete(int position,ElemType &e);
	SqList(const SqList ©);
	SqList& operator = (const SqList ©);

	void Traverse(void(*visit)(ElemType & ))const;
};

template
bool SqList::full()const
{
	return count==maxSize;
}

template
SqList::SqList(int size)

{
	ptr=NULL;
	init(size);
}

template
void SqList::init(int size)
{
	maxSize=size;
	count=0;
	if(ptr!=NULL)
		delete []ptr;
	else
		ptr=new ElemType[maxSize];
}

template
SqList::~SqList()
{
	delete []ptr;
}

template
void SqList::clear()
{
	count=0;
}

template
int SqList::length()const
{
	return count;
}

template
bool SqList::isEmpty()const
{
	return count==0;
}

template
void SqList::Traverse(void(* visit)(ElemType & ))const
{
	for(int curPosition=0;curPosition
StatusCode SqList::setElem(int position,const ElemType &e)
{
	if(position<1||position>count)
		return RANGE_ERROR;
	else
	{
		ptr[position-1]=e;
		return SUCCESS;
	}
}

template
StatusCode SqList::getElem(int position,ElemType &e)const
{
	if(position<1||position>count)
		return RANGE_ERROR;
	else
	{
		e=ptr[position-1];
		return SUCCESS;
	}
}

template
StatusCode SqList::Delete(int position,ElemType &e)
{
	if(position<1||position>count)
		return RANGE_ERROR;
	e=ptr[position-1];
	for(int curPosition=position;curPosition<=count;curPosition++)
		ptr[curPosition-1]=ptr[curPosition];
	count-=1;
	return SUCCESS;
}

template
StatusCode SqList::Insert(int position,const ElemType &e)
{
	//if((position+1)<2||(position+1)>Length())
	if(position<1||position>length()+1)
		return RANGE_ERROR;
	if(full())//注意判断是否线性表已经满了
		return OVER_FLOW;
	for(int curPosition=count;curPosition>=position;curPosition--)
		ptr[curPosition+1]=ptr[curPosition];
	ptr[curPosition]=e;
	count+=1;
	return SUCCESS;
}

template
SqList::SqList(const SqList ©)
{
	init(copy.maxSize);
	
	count=copy.count;
	for(curPosition=0;curPosition
SqList& SqList::operator = (const SqList ©)
{
	if(©!=this)//注意判断copy是否等于本身
	{
		init(copy.maxSize);
		count=copy.count;
		for(curPosition=0;curPosition



你可能感兴趣的:(数据结构书)