C++实现顺序表的插入删除
时间: 2023-10-03 07:05:29 浏览: 126
顺序表的插入删除可以通过以下代码实现:
```c++
#include <iostream>
using namespace std;
// 定义顺序表结构体
struct SeqList {
int* data; // 存储数据的数组
int size; // 当前元素个数
int capacity; // 容量
};
// 初始化顺序表
SeqList* initSeqList(int capacity) {
SeqList* seqList = new SeqList;
seqList->data = new int[capacity];
seqList->size = 0;
seqList->capacity = capacity;
return seqList;
}
// 在顺序表中插入元素
bool insert(SeqList* seqList, int index, int val) {
if (index < 0 || index > seqList->size || seqList->size == seqList->capacity) {
return false;
} else {
for (int i = seqList->size; i > index; i--) {
seqList->data[i] = seqList->data[i-1];
}
seqList->data[index] = val;
seqList->size++;
return true;
}
}
// 在顺序表中删除元素
bool remove(SeqList* seqList, int index) {
if (index < 0 || index >= seqList->size) {
return false;
} else {
for (int i = index + 1; i < seqList->size; i++) {
seqList->data[i-1] = seqList->data[i];
}
seqList->size--;
return true;
}
}
// 打印顺序表
void printSeqList(SeqList* seqList) {
for (int i = 0; i < seqList->size; i++) {
cout << seqList->data[i] << " ";
}
cout << endl;
}
int main() {
SeqList* seqList = initSeqList(5);
// 在顺序表中插入元素
insert(seqList, 0, 1);
insert(seqList, 1, 2);
insert(seqList, 2, 3);
printSeqList(seqList); // 1 2 3
// 在顺序表中删除元素
remove(seqList, 1);
printSeqList(seqList); // 1 3
return 0;
}
```
阅读全文