线性表的实现

线性表是数据结构开始就介绍的一个内容。我看的是c++版的,也是用c++实现的。中间碰到两个小问题,都是因为记性不好造成的。模板类的成员在类外定义时。要注意格式

template<class type> int ArrList<type>::。还有就是类模板的静态常量的初始化。其他没什么了。

<span style="font-size:18px;">#include<iostream>
using namespace std;
template<class type>
class ArrList
{
public:
	ArrList();
	ArrList(type *a,int n);
	~ArrList(){};
	type getlen();
	type getbit(int x);
	int getzhi(type x);
	void insert(type a,int x);
	void delet(int x);
	void printt();
private:
	static int len1;
	int len;
	type date[10000];
};
template<class type>
int ArrList<type>::len1=10000;
template<class type>
ArrList<type>::ArrList()
{
	len=0;
}
template<class type>
ArrList<type>::ArrList(type *a,int n)
{
	len=n;
	for(int i=0;i<n;i++)
	{
		date[i]=a[i];
	}
}
template<class type>
type ArrList<type>::getlen()
{
	return len;
}
template<class type>
type ArrList<type>::getbit(int x)
{
	if(x>=len)
		cout<<"输入不合法"<<endl;
	else
		return date[x-1];
}
template<class type>
int ArrList<type>::getzhi(type x)
{
	int flag=0;
	for(int i=0;i<len;i++)
	{
		if(date[i]==x)
		{
			flag=1;
			return (i+1);
		}
	}
	if(!flag)
		cout<<"找不到值"<<endl;
}
template<class type>
void ArrList<type>::insert(type a,int x)
{
	if(len1<len+1)
		cout<<"数组已满"<<endl;
	else
	{
		int t=date[x];
		date[x]=a;
		for(int i=x+1;i<len+1;i++)
		{
			a=t;
			t=date[i];
			date[i]=a;
		}
		len++;
	}
	
}
template<class type>
void ArrList<type>::delet(int x)
{
	len--;
	for(int i=x;i<len;i++)
	{
		date[i]=date[i+1];
	}
}
template<class type>
void ArrList<type>::printt()
{
	for(int i=0;i<len;i++)
	{
		cout<<date[i]<<" ";
	}
	cout<<endl;
}
int main()
{
	int a[5]={1,2,3,4,5};
	ArrList<int> arr(a,5);
	arr.printt();
	cout<<arr.getlen()<<endl;
	cout<<arr.getbit(2)<<endl;
	cout<<arr.getzhi(2)<<endl;
	arr.insert(0,3);
	arr.printt();
	arr.delet(3);
	arr.printt();
	return 0;
}
</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值