顺序表 C++


#include <iostream>

using namespace std;

const int MaxSize = 100;

template <typename T>

class SeqList {

public:

SeqList();

SeqList(T a[], int n);

~SeqList();

int Length();

T Get(int i);

int Locate(T x);

void Insert(int i, T x);

T Delete(int i);

void Empty();

void PrintList();

private:

T data[MaxSize];

int length;

};

template <typename T>

SeqList<typename T>::SeqList(T a[], int n) {

if (n > MaxSize) throw "参数非法";

length = n;

for (int i = 0; i < n; i++) {

data[i] = a[i];

}

}

template <typename T>

SeqList<typename T>::SeqList():length(0){}

template <typename T>

SeqList<typename T>::~SeqList(){}

template <typename T>

int SeqList<typename T>::Length() {

return length;

}

template <typename T>

T SeqList<typename T>::Get(int i) {

return data[i - 1];

}

template <typename T>

int SeqList<typename T>::Locate(T x) {

for (int i = 0; i < length; i++) {

if (data[i] == x) {

return i+1;

}

}

}

template <typename T>

void SeqList<typename T>::Insert(int i, T x) {

if (length == MaxSize) {

throw "上溢";

}

if (i<1 || i>length + 1) {

throw "插入位置非法";

}

for (int j = length; j >= i; j--) {

data[j] = data[j - 1];

}

data[i - 1] = x;

length ++;

}

template <typename T>

T SeqList<typename T>::Delete(int i) {

T x;

if (length == 0) {

throw "下溢";

}

x = data[i - 1];

if (i<1 || i>length) {

throw "删除位置错误";

}

for (int j = i; j < length; j++) {

data[j - 1] = data[j];

}

length--;

return x;

}

template <typename T>

void SeqList<T>::Empty() {

if (length == 0) {

cout << "是空表" << endl;

}

else {

cout << "不是空表" << endl;

}

}

template <typename T>

void SeqList<T>::PrintList() {

if (length == 0) {

cout << "empty list" << endl;

}

else {

for (int i = 0; i < length; i++) {

cout << data[i] << "\t";

}

cout << endl;

}

}

int main(){

int a[] = { 1,2,3,4,5 };

//SeqList<int> q1 = { a, 5 };

SeqList<int> q1(a,5);

q1.PrintList();

q1.Empty();

cout<<"the second element is:"<<q1.Get(2)<<endl;

cout<<"length of the list is:"<<q1.Length()<<endl;

cout <<"the location 4 of is:"<< q1.Locate(4) << endl;

q1.Insert(2, 8);

q1.PrintList();

q1.Delete(4);

q1.PrintList();

SeqList<int> q2;

q2.PrintList();

return 0;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容