C++静态表的创建

C++静态表的创建,第1张

静态链表的创建: 第一步:链表的定义。
<font size=3>#include <iostream></font>
#include 
using namespace std;
const int MAXSIZE = 100;
template<class T>					//用模板的形式存放静态链表
class StaticList
{
public:
	StaticList() { this->length = 0; }//创建一个空的静态表
	StaticList(T array[], int n);	//复制构造函数
	~StaticList();					//析构函数,删除静态链表
	int Length();					//返回静态链表的长度
	T Get(int i);					//返回第i个位置的值
	int Locate(T x);				//返回x在链表中的位置
	void Insert(int i, T data);		//在链表的第i个位置插入元素data
	void Delete(int i);				//删除第i个位置的元素
	void Printfinfo();				//遍历链表,打印链表的值

private:
	int length;						//记录链表的长度
	T Data[MAXSIZE] = { 0 };				//链表存放的值
};

第二步:有参构造函数的实现:
template<class T >//有参构造函数的实现:
StaticList<T>::StaticList(T array[], int i)
{
	if (i<1 || i>MAXSIZE)
	{
		throw "参数非法!!!";
	}
	for (int j = 0; j < i; j++)
	{
		this->Data[j] = array[j];
	}
	this->length = i;
}
第三步:<获取第i个元素的值>
template<class T>
T StaticList<T>::Get(int i)
{
	if (i<1 || i>MAXSIZE)
	{
		throw"参数非法!!!";
	}
	return data[i - 1];
}
第四步:<根据值找该值在列表中的位置>
template<class T>
int StaticList<T>::Locate(T x)
{
	for (int i = 0; i < MAXSIZE; i++)
	{
		if (Data[i] == x)
		{
			return i+1;
		}
	}
	throw"没找到该值,该值不存在";
}

第五步:<在第i个位置插入值>
template<class T>
void StaticList<T>::Insert(int i, T x)
{
	if (this->length == MAXSIZE||i<1||i>MAXSIZE)
		throw"当前链表数值已满,溢出";
	for (int j = length - 1; j > i - 1; j--)
		Data[j + 1] = Data[j];
	Data[i - 1] = x;
	length++;
}
第六步:<删除第i个位置的元素>
template<class T>
void StaticList<T>::Delete(int i)
{
	if (length == 0 || i<1 || i>MAXSIZE)
		throw"当前链表为空或参数非法!!!";
	for (int j = i - 1; j < length; j++)
	{
		Data[j] = Data[j + 1];
	}
	length--;
}

第七步:<遍历链表,打印链表的值>
template <class T>
void StaticList<T>::Printfinfo()
{
	if (this->length == 0)
		throw"当前链表为空!";
	for (int i = 0; i < length; i++)
	{
		cout << Data[i] << "  ";
			if (i % 4 == 3)
				cout << endl;
	}
}
静态链表附加函数<有序表>
                 //删除有序表中重复的元素//
template <class T>
void DelDup(StaticList<T>& L1)//删除顺序表中重复的元素
{
	for (int i = 0; i < L1.length; i++)
	{
		int j = i + 1;
		while (j < L1.length && L1.Data[i] == L1.Data[j])
			L1.Delete(j);
	}
}
				 //合并有序表之间的元素// 
template <class T>
void Merge(StaticList<T>& L1, StaticList<T>& L2, StaticList<T>& L3)//合并两个顺序表
{
	int i, j, k = 1;
	int n1 = L1.length;
	int n2 = L2.length;
	while (i < n1 && j < n2)
	{
		if (L1.Data[i] < L2.Data[j])
		{
			L3.Insert(k,L1.Data[i])
			i++;
		}
		else if(L1.Data[i] > L2.Data[j])
		{
			L3.Insert(k, L2.Data[j])
			j++;
		}
		k++;
	}

}
ata[i] < L2.Data[j])
		{
			L3.Insert(k,L1.Data[i])
			i++;
		}
		else if(L1.Data[i] > L2.Data[j])
		{
			L3.Insert(k, L2.Data[j])
			j++;
		}
		k++;
	}

记录一下自己第一次发CSDN

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

原文地址:https://54852.com/langs/798192.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存