数据结构-顺序表

数据结构-顺序表,第1张

#include
#define ADD 3					
using namespace std;

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


template
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;			//表指针
};

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/868149.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存