顺序表元素删除c++代码
时间: 2024-09-24 19:29:06 浏览: 42
在C++中,顺序表(也称为数组列表)的元素删除通常涉及到两个步骤:找到需要删除的位置并移动后续元素填充空缺。这里是一个基本的示例,假设我们有一个动态大小的整数顺序表:
```cpp
#include <iostream>
// 顺序表节点结构体
struct Node {
int data;
Node* next;
};
// 动态顺序列表类
class SequentialList {
private:
Node* head; // 链表头指针
public:
// 添加元素到列表尾部
void add(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// 删除指定位置的元素(从0开始)
void removeAt(int position) {
if (position >= 0 && position < size()) {
if (position == 0) {
// 如果要删除的是第一个元素
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* current = head;
for (int i = 0; i < position - 1; ++i) {
current = current->next;
}
if (current == nullptr || current->next == nullptr) {
std::cerr << "Error: Index out of bounds!" << std::endl;
return;
}
current->next = current->next->next;
delete current->next;
}
} else {
std::cerr << "Error: Invalid index!" << std::endl;
}
}
// 返回链表长度
int size() const {
int count = 0;
Node* current = head;
while (current != nullptr) {
++count;
current = current->next;
}
return count;
}
};
int main() {
SequentialList list;
list.add(1);
list.add(2);
list.add(3);
std::cout << "Original list: ";
for (int i = 0; i < list.size(); ++i) {
std::cout << list.get(i) << " ";
}
list.removeAt(1); // 删除第二个元素
std::cout << "\nAfter removing at position 1: ";
for (int i = 0; i < list.size(); ++i) {
std::cout << list.get(i) << " ";
}
return 0;
}
```
阅读全文