顺序表基本操作的代码实现:C++实现
#include<iostream>
using namespace std;
int maxSize = 100;
template <class T>
class SqListClass
{
private:
T *data;
int length;
public:
SqListClass();
~SqListClass();
void CreateList(T a[], int n);
void DispList();
int ListLength();
bool GetElem(int i, T &e);
int LocateElem(T e);
bool ListInsert(int i, T e);
bool ListDelete(int i);
void ReverseList(SqListClass<T> &L);
};
template<class T>
SqListClass<T>::SqListClass()
{
data = new T[maxSize];
length = 0;
}
template<class T>
SqListClass<T>::~SqListClass()
{
delete [] data;
}
template<class T>
void SqListClass<T>::CreateList(T a[], int n)
{
int i;
for(i=0; i<n; i++){
data[i] = a[i];
}
length = i;
}
template<class T>
void SqListClass<T>::DispList(){
cout << "Out:" << endl;
for(int i=0; i<length; i++){
cout << data[i] << " ";
}
cout << endl;
}
template<class T>
int SqListClass<T>::ListLength(){
return length;
}
template<class T>
bool SqListClass<T>::GetElem(int i, T &e){
if(i<0 || i>length) return false;
e = data[i-1];
return true;
}
template<class T>
int SqListClass<T>::LocateElem(T e){
int i = 0;
while(i<length && data[i]!=e) i++;
if(i>=length) return 0;
else return i+1;
}
template<class T>
bool SqListClass<T>::ListInsert(int i, T e){
if(i<0 || i>length) return false;
for(int j=length; j>=i; j--){
data[j]=data[j-1];
}
data[i-1] = e;
length++;
return true;
}
template<class T>
bool SqListClass<T>::ListDelete(int i){
if(i<0 || i>length) return false;
for(int j=i-1; j< length; j++){
data[j] = data[j+1];
}
length--;
return true;
}
template<class T>
void SqListClass<T>::ReverseList(SqListClass<T> &L){
T temp;
for(int j=0; j<L.length/2; j++){
temp = L.data[j];
L.data[j] = L.data[length-j-1];
L.data[length-j-1] = temp;
}
}
int main(){
SqListClass<int> sqList;
int arr[3] = {3,4,5};
sqList.CreateList(arr, 3);
sqList.DispList();
cout << "sqList length is " << sqList.ListLength() << endl;
int a;
sqList.GetElem(2, a);
cout <<"The 2 local is elem " << a << endl;
cout << "The elem 5 local is " << sqList.LocateElem(5) << endl;
sqList.ListInsert(2, 6);
sqList.DispList();
sqList.ListDelete(1);
sqList.DispList();
sqList.ReverseList(sqList);
sqList.DispList();
return 0;
}