线性表的顺序存储结构 顺序表(sequential list) C++

SeqList.h

#ifndef __SEQLIST_H__
#define __SEQLIST_H__

template<class T>
class SeqList
{
public:
	SeqList();
	SeqList(T *_data, int _length);
	virtual ~SeqList();

public:
	int getLength();
	void Insert(int _pos, T _data);
	T Delete(int _pos);
	void setElement(int _pos, T _data);
	T getValue(int _pos);
	int getLocation(T _data);
	void Traverse();

private:
	static const int MaxSize = 100;
	T data[MaxSize];
	int length;
};

#endif // !__SEQLIST_H__

SeqList.cpp

#include <iostream>
#include "SeqList.h"
using namespace std;

/* Constructor && Distructor */
template <class T>
SeqList<T>::SeqList()
{
	length = 0;
}

template <class T>
SeqList<T>::SeqList(T *_data, int _length)
{
	if (_length > MaxSize || _length < 0)
		throw "Illegal Length";
	else
	{
		length = _length;
		for (int i = 0; i < length; i++)
			data[i] = *(_data + i);
	}
}

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

/* Operating Function */
template <class T>
int SeqList<T>::getLength()
{
	return length;
}

template <class T>
void SeqList<T>::Insert(int _pos, T _data)
{
	if (_pos > length || _pos < 0)
		throw "Illegal Posistion";
	for (int i = length; i >= _pos; i--)
		data[i] = data[i - 1];
	data[_pos - 1] = _data;
	length += 1;
}

template <class T>
T SeqList<T>::Delete(int _pos)
{
	T tempData = data[_pos];

	if (_pos > length || _pos <= 0)
		throw "Illegal Posistion";
	for (int i = _pos - 1; i < length - 1; i++)
		data[i] = data[i + 1];
	length -= 1;

	return tempData;
}

template <class T>
void SeqList<T>::setElement(int _pos, T _data)
{
	if (_pos > length || _pos < 0)
		throw "Illegal Posistion";

	data[_pos - 1] = _data;
}

template <class T>
T SeqList<T>::getValue(int _pos)
{
	if (_pos > length || _pos < 0)
		throw "Illegal Posistion";
	else
		return data[_pos - 1];
}

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

template <class T>
void SeqList<T>::Traverse()
{
	for (int i = 0; i < length; i++)
		cout << data[i] << " ";
	cout << endl;
}

Sequential.cpp

#include <iostream>
#include "SeqList.h"
#include "SeqList.cpp"
using namespace std;

int main()
{
	int arr[5] = { 0, 0, 0, 0, 0 };
	SeqList<int> list(arr, 5);

	list.Traverse();

	list.Insert(1, 1);
	list.Traverse();

	list.Delete(1);
	list.Traverse();

	list.setElement(2, 2);
	list.Traverse();

	cout << list.getValue(2) << endl;
	cout << list.getLocation(2) << endl;
	cout << list.getLength() << endl;

	return 0;
}

输出结果:

0 0 0 0 0
1 0 0 0 0 0
0 0 0 0 0
0 2 0 0 0
2
2
5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白水baishui

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

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

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

打赏作者

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

抵扣说明:

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

余额充值