重学数据结构之顺序表

还是把顺序表从头到尾温习了一遍。

顺序表是线性表按照顺序存储结构存储的。我们按顺序将数据存储到存储空间中,所以存储单元的地址是连续的,即元素序号与存放它的数组下标一一对应。

序号通常从1开始,而下标从0开始,所以第i个元素的下标则是[i-1]。

我们用数组存放数据,数组的初始化必先定义长度,下文中我们用MaxSize来表示线性表总共占用的存储空间,而用length表示实际占用(length之后的空间也是被占用的,但无数据,当作“不占用”)。

一旦我们知道顺序表的起始地址,计算任意一个元素的存储地址的时间是相等的。这种存储结构叫做随机存取结构。

#include <iostream>
using namespace std;

const int MaxSize = 1000;
template <class T>
class SeqList
{
	public:
		SeqList();
		SeqList(T a[], int n);
		~SeqList();
		int Length();	//获取长度 
		T Get(int i);	// 获取data[i-1] 
		int Locate(T x);// x的下标加1 
		void Insert(int i, T x);// 在第i个位置插入值为x的元素 
		T Delete(int i);// 删除第i个元素
		void Output();	// 遍历打印 
	private:
		T data[MaxSize];
		int length;
};
template <class T>
SeqList<T>::SeqList()
{
	length = 0;
}

template <class T>
SeqList<T>::SeqList(T a[], int n)
{
	if (n > MaxSize) throw"参数非法";
	for(int i = 0; i < n ; i++)
		data[i] = a[i];
	length = n;
}

template <class T>
SeqList<T>::~SeqList()
{
}

template <class T>
SeqList<T>::Length()
{
	return length;
}

template <class T>
T SeqList<T>::Get(int i)
{
	// 可查找位置为1~length
	if(i < 1 || i > length) throw"位置";
	return data[i-1];
}

template <class T>
int SeqList<T>::Locate(T x)
{
	for(int i = 0 ; i < length; i++)
	{
		if(data[i] == x) return i + 1;
	}
	return 0; 
}

template <class T>
void SeqList<T>::Insert(int i, T x)
{
	// 可插入位置为1~length+1
	if(i <= 0 || i > length + 1 )	throw"位置";
	if(length == MaxSize) throw "上溢";
	for(int j = length ; j >= i ;j--)
		data [j] = data[j-1]; 
	data[i-1] = x;
	length ++;
}

template <class T>
T SeqList<T>::Delete(int i)
{
	// 可删除位置为1~length
	// 删除data[i-1] 
	if(i <= 0 || i >= length) throw"位置";
	if (length == 0) throw "下溢"; 
	T x = data[i-1];
	for (int j = i; j <= length - 1 ;j++)
		data[j-1] = data[j]; 
	length --; 
	return x;	// 最后返回才能移动各元素 
}

template <class T>
void SeqList<T>::Output()
{
	for(int i = 0 ; i < length; i++)
		cout << data[i] << "  ";
 } 
int main()
{
	// 无参构造 
	SeqList<double> a;
	a.Insert(1,1);	a.Insert(2,3);	a.Insert(3,4);
  	// a.Insert(5,8)
  	a.Output();
  	cout << "插入数据后a的长度是:\t" << a.Length() << endl;
  	
  	//有参构造 
  	double b[6] = {1.1, 2.1, 3.1, 4.1, 0, 6.1};
	SeqList<double> SL(b,6);
	SL.Output(); 
	
	// 按位查找
	cout << "第" << 4 << "个结点值为:\t" << SL.Get(4) << endl;
	// 查找第一个值为x的结点的序数
	cout << "值为1.1的结点序数为:\t" << SL.Locate(1.1) << endl;
	cout << "值为2.7的结点序数为:\t" << SL.Locate(2.7) << endl;
	// 删除序数为i的结点
	double temp = SL.Delete(5);
	cout << "删除第5个结点" << temp <<"后\t";
	SL.Output(); 
}

------------------------19.6.2 待续----------------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值