顺序表的实现基本操作代码
时间: 2024-12-14 16:26:28 浏览: 18
顺序表是一种简单的线性数据结构,它通过数组的方式存储元素,每个元素在内存中连续存储。以下是顺序表的基本操作及其对应的C++代码实现:
1. **初始化**:
- 创建一个固定大小的数组,并分配空间。
```cpp
class SeqList {
private:
int* elements; // 存储元素的数组
int size;
int capacity;
public:
SeqList(int initial_capacity) {
elements = new int[initial_capacity];
size = 0;
capacity = initial_capacity;
}
};
```
2. **插入元素**(在列表末尾):
```cpp
void insert(int value) {
if (size == capacity) {
resize(capacity * 2); // 当满时,扩容
}
elements[size++] = value;
}
void resize(int new_capacity) {
int* new_elements = new int[new_capacity];
for (int i = 0; i < size; i++) {
new_elements[i] = elements[i];
}
delete[] elements;
elements = new_elements;
capacity = new_capacity;
}
```
3. **删除元素**(指定位置):
```cpp
void removeAt(int index) {
if (index >= 0 && index < size) {
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
if (size < capacity / 4 && capacity > 0) { // 缩容条件
resize(capacity / 2);
}
} else {
throw std::out_of_range("Index out of range");
}
}
```
4. **查找元素**:
```cpp
bool find(int value) const {
for (int i = 0; i < size; i++) {
if (elements[i] == value) {
return true;
}
}
return false;
}
```
5. **遍历**:
```cpp
void traverse() const {
for (int i = 0; i < size; i++) {
std::cout << elements[i] << " ";
}
std::cout << "\n";
}
```
阅读全文