实现了顺序表的一些最基本功能。。。。
#pragma once
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
const int MAXSIZE = 1000;//顺序表的最大长度
using Position = int;
template<typename T>
class SeqList {
public:
SeqList();//顺序表的默认构造函数,创建一个空表
SeqList(const T copy[], int n);//传入数组构造线性表
SeqList& operator =(const SeqList<T>& S);//copy assignment操作符
Position Find(const T& x);//查找元素
bool Insert(const T& x, const int& i);//在第i个位序插入元素x
bool Delete(const int& i);//删除第i个位序的元素
bool push_back(const T& x);//在尾部插入元素x
const int& length();
private:
T dataList[MAXSIZE];//线性表的最大空间
Position Last;//线性表最后一个元素的下标
};
template<typename T>
SeqList<T>::SeqList()
{
Last = -1;
}
template<typename T>
SeqList<T>::SeqList(const T copy[],int n)
{//n是传入数组的大小
if (n <= MAXSIZE) {
Last = -1;
for (int i = 0; i < n; ++i) {
dataList[i] = copy[i];
++Last;
}
}
else
cout << "传入的数组参数过大" << endl;
}
template<typename T>
SeqList<T>& SeqList<T>::operator =(const SeqList<T>& S)
{
Last = -1;
int length = sizeof(S.dataList) / sizeof(S.dataList[0]);
for (int i = 0; i < length; ++i) {
dataList[i] = S.dataList[i];
++Last;
}
return *this;
}
#define ERROR -1
template<typename T>
Position SeqList<T>::Find(const T& x)
{
Position i = 0;
while (i <= Last && dataList[i] != x) {
++i;
}
if (i > Last)
return ERROR;
else
return i;
}
template<typename T>
bool SeqList<T>::Insert(const T& x, const int& i)
{
if (Last == MAXSIZE - 1) {
cout << "表空间已满,不能插入" << endl;
return false;
}
if (i<1 || i>Last + 2) {
cout << "插入的位序不合法" << endl;
}
for (Position j = Last; j >= i - 1; --j)
dataList[j + 1] = dataList[j];//将位序i及以后的元素顺序向后移动一位
dataList[i - 1] = x;
++Last;
return true;
}
template<typename T>
bool SeqList<T>::Delete(const int& i)
{
if (i<1 || i>Last + 1) {
cout << "位序" << i << "不存在元素" << endl;
return false;
}
for (Position j = i - 1; j < Last; ++j)
dataList[j] = dataList[j + 1];
--Last;
return true;
}
template<typename T>
bool SeqList<T>::push_back(const T& x)
{
if (Last == MAXSIZE - 1) {
cout << "表空间已满,不能插入" << endl;
return false;
}
dataList[Last + 1] = x;
++Last;
return true;
}
template<typename T>
const int& SeqList<T>::length()
{
return Last + 1;
}
#include"SeqList.h"
int main()
{
class SeqList<int> L {}, L1{};
int x{};
int arr[4]{ -1,-2,-3,-4 };
for (int i = 0; i < 8; ++i) {
cin >> x;
L.push_back(x);
}
cout << L.Find(8) << endl;
L.Insert(9, 9);
cout << L.Find(9) << endl;
L.Delete(9);
cout << L.Find(9) << endl;
L1 = L;
cout << L1.Find(7) << endl;
int n = sizeof(arr) / sizeof(arr[0]);
class SeqList<int> L2 { arr,n };
cout << L2.Find(-3) << endl;
cout << L2.length() << endl;
return 0;
}