C++学习之顺序表

    xiaoxiao2021-03-25  120

    #include< iostream > using namespace std; /* 用C++实现顺序表,存储10个整型数据,实现插入、修改、删除元素和输出整个顺序表的功能 函数中的location、index都为数组下标,非逻辑序号 */ //线性表数据结构` template <typename DataType> class SeqList { public: //构造函数 SeqList(int size = defaultSize) { if (size > 0)//检查赋予的顺序表大小,如果合法则分配相应大小的内存 { maxSize = size; length = 0; elements = new DataType[maxSize];//分配内存大小 for (int i = 0; i < maxSize; i++) { elements[i] = NULL; } } } //析构函数 ~SeqList() { delete[] elements; } bool insertElement(DataType data);//向表尾插入新元素 bool deletElement(int location);//删除指定位置的元素 DataType getElement(int location);//返回指定位置的元素 bool changeElement(int location, DataType newData);//修改指定位置的元素值 int getlength() { return length; } private: static const int defaultSize = 10;//设置默认顺序表大小 DataType *elements; int maxSize;//顺序表最大大小 int length;//顺序表的有效长度 }; template <typename DataType> bool SeqList<DataType>::insertElement(DataType data) { int currentIndex = length;//记录新元素的插入位置 if (length > maxSize) { return false; } else { elements[currentIndex] = data; length++; return true; } } template <typename DataType> DataType SeqList<DataType>::getElement(int location) { if (location<0 || location>length) { cout << "参数无效" << endl; return 0; } else { return elements[location]; } } template <typename DataType> bool SeqList<DataType>::deletElement(int location) { if (location<0 || location>length) { return false; } else { for (int i = location; i < length; i++) { elements[i] = elements[i + 1]; } length--; return true; } } template <typename DataType> bool SeqList<DataType>::changeElement(int location, DataType newData) { if (location < 0 || location >= length) { return false; } else { elements[location] = newData; return true; } } int main() { SeqList<int> list(10); for (int i = 0; i < 10; i++) { list.insertElement(i * 10); } for (int i = 0; i < list.getlength(); i++) { cout << list.getElement(i) << " "; } cout << endl; list.deletElement(3); for (int i = 0; i < list.getlength(); i++) { cout << list.getElement(i) << " "; } cout << endl; list.changeElement(5, 44); for (int i = 0; i < list.getlength(); i++) { cout << list.getElement(i) << " "; } cout << endl; }
    转载请注明原文地址: https://ju.6miu.com/read-6012.html

    最新回复(0)