C++线性表

C++线性表(arrayList)

一、线性表的定义

线性表是由一个或多个数据元素组成的有限序列
线性表根据存储方式分为:
1、顺序存储(数组描述):元素的地址是连续的
2、链式存储(链表描述):节点地址不连续,通过指针连起来

二、线性表的抽象数据类型

线性表的抽象类(常用的API):

  • 判断是否为空;
  • 返回元素个数;
  • 返回索引元素;
  • 返回指定元素第一次出现的索引值;
  • 删除索引元素;
  • 将指定元素插入指定索引位置;
#include<iostream>
#include<algorithm>
using namespace std;
//父类线性表
template<class T>
class LineList
{
   
public:
	virtual ~LineList() {
   };                                         //虚析构函数
	virtual bool empty() const = 0;                                 //判断线性表是否为空
	virtual int size() const = 0;                                   //返回线性表大小
	virtual T& get(int theIndex) const = 0;                         //按索引查找元素
	virtual int index(const T& theElement) const = 0;               //按值查找元素
	virtual void erase(int theIndex) = 0;                           //删除索引元素
	virtual void insert(int theIndex, const T& theElement) = 0;     //按索引插入元素
};

三、线性表的顺序存储

  对于顺序存储方式一般用数组实现,事实上就是在内存中找个初始地址,然后通过占位的形式,把一定连续的内存空间给占了,然后把相同数据类型的数据元素依次放在这块空地中,数组大小有两种方式指定,一是静态分配,二是动态扩展。
  顺序表相关的操作跟数组有关,一般都是移动数组元素。
在这里插入图片描述顺序存储的实现方式:

//子类线性表,通过数组实现
template<class T>
class arrayList : public LineList<T>
{
   
public:
	arrayList(int initialCapacity = 10);
	arrayList(const arrayList<T>&);
	~arrayList() {
    delete[] element; }
	bool empty() const
	{
   
		if (ListSize == 0)
			return 1;
		else
			return 0;
	}
	int size() const {
    return ListSize; }
	T& get(int theIndex) const;
	int index(const T& theElement) const;
	void erase(int theIndex);
	void insert(int theIndex, const T& theElement);
	void output() const;
	int capacity() const {
    return arrayLength; }
protected:
	void checkIndex(int theIndex) const;
	T* element;
	int arrayLength;
	int ListSize;
};

各成员函数:

template<class T>
arrayList<T>::arrayList(int initialCapacity)
{
   
	if (initialCapacity < 1)
		cout<<"Capability must be greater than 1"<<endl;
	arrayLength = initialCapacity;
	element = new T[arrayLength];
	ListSize = 0;
}

template<class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{
   
	arrayLength = theList.arrayLength;
	ListSize = theList.ListSize;
	element = new T[arrayLength];
	copy(theList.element, theList.element + ListSize, element);
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值