用c++写一个顺序表的简单操作程序

#include<iostream>
using namespace std;
template <class T>
class List
{
public:
	List(int MaxSize = 10);
	virtual~List(){ delete[] element; }
	bool IsEmpty() const { return(length == 0); }             
	int Length() const { return length; }                    //const表示返回值不能被修改。
	bool Find(int k, T & x) const;                          //返回第k个元素保存至x中; &x 是引用传值。
	int Search(const T & x) const;                         //为避免实参被修改,就用const修饰,更安全。
	List<T>& Insert(int k, const T & x);
	List<T>& Delete(int k, T & x);
	int size() const { return MaxSize; }
	void show();
	void output(ostream& out);              //这里定义了一个成员函数,避免使用友元函数进行重载<<。
private:
	int length;
	int MaxSize;
	T *element;                // 一维动态数组
};

template <class T>
List<T>::List(int size){
	MaxSize = size;
	element = new T[MaxSize];
	length = 0;
}
template <class T>
bool List<T>::Find(int k, T & x) const{
	if (k<0 || k>length - 1)   return false;
	x = element[k];      return true;
}
template <class T>
int List<T>::Search(const T & x) const{
	for (int i = 0; i < length; i++)
	if (x == element[i])   return i;
	return 0;
}
template <class T>
List<T>& List<T>::Insert(int k, const T & x){
	if (k<0 || k>MaxSize - 1)     cout << "The position is wrong!" << endl;
	else if (length == MaxSize)    cout << "beyond the MaxSize!" << endl;
	else{
		for (int i = length; i > k; i--){
			element[i - 1] = element[i];
		}
		element[k] = x;
		length++;
	}
	return *this;
}
template <class T>
List<T>& List<T>::Delete(int k, T & x){
	if (Find(k, x)){
		for (int i = k; i < length - 1; i++)   
			element[i] = element[i + 1];
		length--;
	}
	return *this;
}
template <class T>
void List<T>::show(){
	for (int i = 0; i < length; i++){
		cout << element[i] << " ";
	}
	cout<< endl;
}
template <class T>
void List<T>::output(ostream& out){
	for (int i = 0; i < length; i++){
		out << element[i] << " ";
	}
}
template <class T>
ostream & operator<<(ostream& out, List<T>& x){
	x.output(out);
	return out;
}
void main(){
	List<int> MyList(5);
	cout << "MaxSize: " << MyList.size() << endl;
	cout << "IsEmpty: " << MyList.IsEmpty() << endl;
	cout << "Length: " << MyList.Length() << endl;
	MyList.Insert(0, 1).Insert(1, 2).Insert(2, 3).Insert(3, 4);
	cout << "MyList is: "; MyList.show(); cout << endl;

	int z;
	MyList.Find(1,z);
	cout << "The element in the position of 1 is : " << z << endl;
	cout << "The element 4 is in the position of :  " << MyList.Search(4) << endl;
	MyList.Delete(3, z);
	cout << "The delete element is: " << z << endl;
	cout << "MyList is: " << MyList << endl;
	cout << "Length: " << MyList.Length() << endl;
	system("pause");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值