C++类模板实现线性表的顺序存储

类的定义

首先定义一个类,这个类应该包含私有属性线性表长度length、线性表容量capacity、线性表的数据缓冲区list_buf,以及线性表操作相关的方法。和C语言实现线性表不同的是,C++类中有构造函数和析构函数,会自动管理内存,所以也就不用创建链表和销毁链表的操作了。类的定义如下

template<typename MyType>
class SeqList
{
public:
	SeqList(int capacity);
	~SeqList();
public:
	int get_length();
	MyType get_data(int pos);
	int insert(MyType& node, int pos);
	MyType delet(int pos);
	int get_capacity();
	void clear();
private:
	int length;
	int capacity;
	MyType* list_buf;
};

成员方法的实现

template<typename MyType>
SeqList<MyType>::SeqList(int capacity)
{
	this->list_buf = new MyType[capacity];
	this->capacity = capacity;
	this->length = 0;
}

template<typename MyType>
SeqList<MyType>::~SeqList()
{
	if (this->list_buf != NULL)
	{
		delete[] this->list_buf;
		this->list_buf = NULL;
	}
	this->capacity = 0;
	this->length = 0;
}

template<typename MyType>
int SeqList<MyType>::get_length()
{
	return this->length;
}

template<typename MyType>
MyType SeqList<MyType>::get_data(int pos)
{
	return this->list_buf[pos];
}

template<typename MyType>
int SeqList<MyType>::insert(MyType& node, int pos)
{
	int i = 0;
	for (i = this->length; i > pos; i--)
	{
		this->list_buf[i] = this->list_buf[i - 1];
	}
	this->list_buf[i] = node;
	this->length++;
	return 0;
}

template<typename MyType>
MyType SeqList<MyType>::delet(int pos) //返回元素,不能返回引用,因为pTemp是局部变量
{
	MyType pTemp = this->list_buf[pos];
	for (int i = pos + 1; i < this->length; i++)
	{
		this->list_buf[i - 1] = this->list_buf[i];
	}
	this->length--;
	return pTemp;
}

template<typename MyType>
int SeqList<MyType>::get_capacity()
{
	return this->capacity;
}

template<typename MyType>
void SeqList<MyType>::clear()
{
	this->length = 0;
}

线性表的实现建议C++和C语言一块对比学习,这样可以进一步理解C++和C的区别,C++通过this指针隐藏了一个参数,在成员方法中不用像C语言一样需要把一个线性表句柄传入参数了。C语言实现线性表的顺序存储可以参考

【数据结构】线性表的顺序存储API及实现icon-default.png?t=M276https://blog.csdn.net/qq_43471489/article/details/123762070另外,本文的代码也已经上传,可以在我的资源中免费下载。

posted @ 2022-04-06 08:00  Mindtechnist  阅读(17)  评论(0编辑  收藏  举报  来源