c++线性表的数组实现
时间: 2023-08-18 12:05:12 浏览: 59
C++中可以使用数组来实现线性表。以下是一个简单的示例代码:
```cpp
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 线性表最大长度
class ArrayLinearList {
private:
int data[MAXSIZE]; // 存储线性表元素
int length; // 线性表长度
public:
ArrayLinearList() {
length = 0;
}
// 在位置i插入元素e
bool insert(int i, int e) {
if (i < 1 || i > length+1 || length == MAXSIZE) {
return false;
}
for (int j = length; j >= i; j--) {
data[j] = data[j-1];
}
data[i-1] = e;
length++;
return true;
}
// 删除位置i的元素
bool remove(int i) {
if (i < 1 || i > length) {
return false;
}
for (int j = i; j < length; j++) {
data[j-1] = data[j];
}
length--;
return true;
}
// 获取位置i的元素
bool get(int i, int& e) {
if (i < 1 || i > length) {
return false;
}
e = data[i-1];
return true;
}
// 输出线性表元素
void display() {
for (int i = 0; i < length; i++) {
cout << data[i] << " ";
}
cout << endl;
}
};
int main() {
ArrayLinearList list;
list.insert(1, 10);
list.insert(2, 20);
list.insert(3, 30);
list.display();
int e;
list.get(2, e);
cout << "位置2的元素为:" << e << endl;
list.remove(2);
list.display();
return 0;
}
```
以上代码实现了一个简单的数组线性表,包含了插入、删除、获取元素和输出元素等基本操作。