数据结构-顺序表(c++)

#include<iostream>
#define ADD 3					
using namespace std;

//非内置数据类型可以使用操作符重载进行数据的比较


template<typename T>
class List
{
public:
	//线性表的初始化
	List(int n = 10){this->length = 0;this->max = n;this->L = new T[max];}

	//线性表的销毁
	~List()
	{
		if (this->L != NULL) { delete[] this->L; }
		cout << "顺序表已销毁!" << endl;
	}

	//插入元素到某一位置
	void insertElem(int loc, T elem)
	{
		//当容量不够容纳时进行扩容
		if (length >= this->max)
		{
			cout << "空间已满,正在扩容!" << endl;
			T* temp = new T[this->max];

			for (int i = 0; i < this->max; i++) {temp[i] = this->L[i];}

			delete[] this->L;
			this->L = new T[this->max + ADD];

			for (int i = 0; i < this->max; i++) { this->L[i] = temp[i]; }
			this->max += ADD;

			cout << "扩容完毕,正在准备插入!" << endl;
		}

		//根据给出的位置进行插入
		
		//尾插
		if (loc >= this->length || length == 0)
		{
			L[length] = elem;
			this->length++;
			cout << "尾部插入!" << endl;
		}
		//头插
		else if (loc <= 1)
		{
			for (int i = this->length; i > 0; i--) { L[i] = L[i - 1]; }
			L[0] = elem;
			this->length++;
			cout << "头部插入!" << endl;
		}
		//中间插
		else if (loc > 1 && loc < this->length)
		{
			for (int i = length; i >= loc; i--) { L[i] = L[i - 1]; }
			L[loc] = elem;
			this->length++;
			cout << loc << "处插入!" << endl;
		}
	}

	//删除某一位置的元素
	void deleteElem(int loc)
	{
		if (loc < 1 || loc > length) { cout << "位置不存在!" << endl; }

		//中间删
		if (loc > 1 && loc < length)
		{
			for (int i = loc - 1; i < length; i++) { L[i] = L[i + 1]; }
			this->length--;
			cout << loc << "位删除成功!" << endl;
		}

		//头删
		else if (loc == 1)
		{
			for (int i = loc - 1; i < length; i++) { L[i] = L[i + 1]; }
			this->length--;
			cout << "头删除成功!" << endl;
		}

		//尾删
		else if (loc == length) { this->length--; cout << "尾删除成功!" << endl; }
	}

	//遍历
	void printList(){for (int i = 0; i < this->length; i++) { cout << i + 1 << "\t" << this->L[i] << endl; }}

	//按值查找
	void findElem(T elem) 
	{
		for (int i = 0; i < this->length; i++)
		{	
			if (L[i] == elem) { cout << "位置:" << i + 1 << "\t值:" << L[i] << endl; }
		}
	}

	//返回表长
	int lengthList() { if (this->length == 0) { return 0; } return this->length; }

	//判断是否为空表
	bool nullList() { if (this->length == 0) { return true; }return false; }

	//清空线性表
	void removeList() { this->length = 0; delete L; new T[max]; }

	//返回最大容量
	int maxVolume() { return this->max; }

private:

	int max;		//记录最大表长
	int length;		//记录当前表长
	T* L;			//表指针
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心若雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值