编写代码实现顺序表的类型定义及顺序表的初始化、销毁、插入、删除、取元素等操作
时间: 2024-10-15 07:15:25 浏览: 28
python实现顺序表的简单代码
在编写代码实现顺序表(也称为线性表)时,我们通常会定义一个结构体或类来存储数据,并包含一些基本的操作方法。这里是一个简单的C++示例:
```cpp
// 定义顺序表节点
struct ListNode {
int data; // 数据域
ListNode* next; // 指向下一个节点的指针
};
// 顺序列表类型定义
class SequentialList {
private:
ListNode* head; // 链表头指针
int size; // 列表长度
public:
// 初始化顺序表
SequentialList() : head(nullptr), size(0) {}
// 销毁顺序表
~SequentialList() {
while (head != nullptr) {
ListNode* temp = head;
head = head->next;
delete temp;
}
size = 0;
}
// 插入元素
void insert(int value, int position) {
if (position < 0 || position > size)
return;
ListNode* newNode = new ListNode{value};
if (position == 0) {
newNode->next = head;
head = newNode;
} else {
ListNode* current = head;
for (int i = 0; i < position - 1 && current != nullptr; ++i)
current = current->next;
newNode->next = current->next;
current->next = newNode;
}
size++;
}
// 删除元素
bool remove(int value) {
if (size == 0)
return false;
if (head->data == value) {
ListNode* temp = head;
head = head->next;
delete temp;
size--;
return true;
}
ListNode* current = head;
while (current->next != nullptr && current->next->data != value)
current = current->next;
if (current->next == nullptr)
return false;
ListNode* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
size--;
return true;
}
// 取元素
int get(int index) const {
if (index < 0 || index >= size)
throw std::out_of_range("Index out of range");
ListNode* current = head;
for (int i = 0; i < index; ++i)
current = current->next;
return current->data;
}
};
阅读全文