顺序表实现动态完整代码
时间: 2023-05-18 07:05:23 浏览: 65
以下是一个简单的顺序表实现动态完整代码:
```c++
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 定义最大容量
template <typename T>
class SeqList {
private:
T* data; // 存储数据的数组
int length; // 当前长度
int maxSize; // 最大容量
public:
SeqList(int size = MAXSIZE) { // 构造函数
data = new T[size];
length = 0;
maxSize = size;
}
~SeqList() { // 析构函数
delete[] data;
}
int getLength() const { // 获取当前长度
return length;
}
bool isEmpty() const { // 判断是否为空
return length == 0;
}
bool isFull() const { // 判断是否已满
return length == maxSize;
}
bool insert(int i, const T& x) { // 在指定位置插入元素
if (i < 0 || i > length || isFull()) {
return false;
}
for (int j = length; j > i; j--) {
data[j] = data[j - 1];
}
data[i] = x;
length++;
return true;
}
bool remove(int i) { // 删除指定位置的元素
if (i < 0 || i >= length || isEmpty()) {
return false;
}
for (int j = i; j < length - 1; j++) {
data[j] = data[j + 1];
}
length--;
return true;
}
int search(const T& x) const { // 查找元素
for (int i = 0; i < length; i++) {
if (data[i] == x) {
return i;
}
}
return -1;
}
T& operator[](int i) { // 重载下标运算符
return data[i];
}
const T& operator[](int i) const { // 重载下标运算符(常量版本)
return data[i];
}
};
int main() {
SeqList<int> list;
for (int i = 0; i < 10; i++) {
list.insert(i, i);
}
for (int i = 0; i < list.getLength(); i++) {
cout << list[i] << " ";
}
cout << endl;
list.remove(5);
for (int i = 0; i < list.getLength(); i++) {
cout << list[i] << " ";
}
cout << endl;
int index = list.search(3);
if (index != -1) {
cout << "3 is at index " << index << endl;
} else {
cout << "3 is not found" << endl;
}
return 0;
}
```