顺序表基本操作的实现说明:实现SeqList类模板基本操作包括无参构造函数、有参构造函数、求顺序表的表长、按位查找、按值查找、插入、删除、遍历等并在主函数中对各种操作进行验证。1 实验代码在此补充代码如果有多个文件则分多个文件1SeqListh……2SeqListcpp……3SeqListMaincpp……2 实验运行结果实验数据可参考如下:执行插入操作前数据为:4 2 6 8 12 10 14
(1) SeqList.h
#ifndef SEQLIST_H
#define SEQLIST_H
template<class T>
class SeqList {
private:
T* data; // 顺序表的存储空间
int length; // 顺序表的长度
int maxSize; // 顺序表的最大容量
public:
// 构造函数
SeqList();
SeqList(int maxSize);
// 析构函数
~SeqList();
// 求顺序表的表长
int getLength();
// 按位查找
T get(int i);
// 按值查找
int locate(T x);
// 插入
bool insert(int i, T x);
// 删除
bool remove(int i);
// 遍历
void printList();
};
template<class T>
SeqList<T>::SeqList() {
maxSize = 10;
data = new T[maxSize];
length = 0;
}
template<class T>
SeqList<T>::SeqList(int maxSize) {
this->maxSize = maxSize;
data = new T[maxSize];
length = 0;
}
template<class T>
SeqList<T>::~SeqList() {
delete[] data;
}
template<class T>
int SeqList<T>::getLength() {
return length;
}
template<class T>
T SeqList<T>::get(int i) {
if (i < 0 || i >= length) {
throw "Index out of range";
}
return data[i];
}
template<class T>
int SeqList<T>::locate(T x) {
for (int i = 0; i < length; i++) {
if (data[i] == x) {
return i;
}
}
return -1;
}
template<class T>
bool SeqList<T>::insert(int i, T x) {
if (i < 0 || i > length) {
return false;
}
if (length >= maxSize) {
return false;
}
for (int j = length - 1; j >= i; j--) {
data[j+1] = data[j];
}
data[i] = x;
length++;
return true;
}
template<class T>
bool SeqList<T>::remove(int i) {
if (i < 0 || i >= length) {
return false;
}
for (int j = i; j < length - 1; j++) {
data[j] = data[j+1];
}
length--;
return true;
}
template<class T>
void SeqList<T>::printList() {
for (int i = 0; i < length; i++) {
cout << data[i] << " ";
}
cout << endl;
}
#endif
(2) SeqList.cpp
#include "SeqList.h"
#include <iostream>
using namespace std;
int main() {
SeqList<int> list(20);
// 插入操作
list.insert(0, 4);
list.insert(1, 2);
list.insert(2, 6);
list.insert(3, 8);
list.insert(4, 12);
list.insert(5, 10);
list.insert(6, 14);
list.insert(7, 16);
list.insert(8, 19);
list.insert(9, 18);
cout << "执行插入操作前数据为:" << endl;
list.printList();
list.insert(5, 11);
cout << "执行插入操作后数据为:" << endl;
list.printList();
// 按值查找
int index = list.locate(16);
cout << "值为16的元素位置为:" << index << endl;
// 删除操作
list.remove(6);
cout << "执行删除第7个元素,删除前数据为:" << endl;
list.printList();
return 0;
}
(3) SeqListMain.cpp
#include "SeqList.cpp"
``
原文地址: https://www.cveoy.top/t/topic/iQcE 著作权归作者所有。请勿转载和采集!