线性表的顺序实现,动态数组。
?、、、c++
#
```c++
#include<iostream>
using namespace std;
const int initsize = 100;
const int Maxsize = 100;
class seqlist {//动态数组的数据结构定义
public:
int* data;
int length;//当前长度
int maxsize;//最大容量
};
seqlist L;
void init() {//初始化
L.data = new int[initsize];
L.length = 0;
L.maxsize = Maxsize;
}
bool insert(seqlist& L, int index, int e) {//在数组第i个位置插入元素e
if (index<0 || index>L.length) return false;
else if (L.length >= Maxsize) return false;
for (int j = L.length - 1; j >= index; j--) L.data[j + 1] = L.data[j];
L.data[index] = e;
L.length++;
return true;
}
int findByVal(seqlist L,int val) {//按值查找 并返回第一个在数组中的位置 找不到返回-1;
for (int index = 0; index < L.length; index++) {
if (L.data[index] == val) return index;
return -1;
}
}
int findByIndex(seqlist L, int index) {//按位查找 下标不符合返回-1,否则返回下标对应的值
if (index<0 || index>L.length - 1) return -1;
return L.data[index];
}
bool deleteByIndex(seqlist& L, int index) {//删除指定下标的元素
if (index<0 || index>L.length - 1) return false;
for (int i = index + 1; i <= L.length - 1; i++) L.data[i - 1] = L.data[i];
L.length--;
return true;
}
bool deleteByVal(seqlist& L, int val) {
int index = 0;
for (int i = 0; i < L.length; i++) {
if (L.data[i] == val) index = i;
}
deleteByIndex(L, index);
return true;
}
void desList(seqlist& L) {//销毁L
L.data = nullptr;
L.length = 0;
}
void printSeqList(seqlist& L) {
for (int i = 0; i < L.length; i++) cout << L.data[i]<<" ";
cout<<endl;
}
void add(seqlist& L) {//当数组长度不够时扩容为2倍
seqlist L2;
L2.data = new int[Maxsize * 2];
for (int i = 0; i < L.length; i++) L2.data[i] = L.data[i];
L2.length = L.length;
delete [] L.data;
L.data = new int[Maxsize * 2];
for (int i = 0; i < L.length; i++) L.data[i] = L2.data[i];
L.length = L2.length;
delete[] L2.data;
}
int main() {
init();
for (int i = 0; i < 10; i++) {
L.data[i] = i;
L.length = 10;
}
printSeqList(L);
insert(L, 2, 100);
printSeqList(L);
deleteByIndex(L, 5);
printSeqList(L);
deleteByVal(L, 100);
printSeqList(L);
add(L);
for (int i = 9; i < 200; i++) {
L.data[i] = i;
L.length++;
}
printSeqList(L);
return 0;
}
```
?运行结果如上图所示。
当输入250个值的时候,因为容量再次不足,所以报错。
?
|