1用c++写一个顺序表,实现增删查改操作
时间: 2024-11-03 14:20:23 浏览: 7
顺序表的增删查改以及拼接操作SqList.cpp
在C++中,我们可以使用结构体或类来创建一个简单的顺序表,比如使用动态数组存储元素。这里是一个基础的顺序表实现,包含了插入、删除、查找和修改操作:
```cpp
#include <iostream>
using namespace std;
// 定义顺序表节点
struct ListNode {
int data;
ListNode* next;
};
class SequenceList {
private:
ListNode* head; // 头结点
int size; // 当前列表长度
public:
// 构造函数
SequenceList() : head(nullptr), size(0) {}
// 插入操作
void insert(int value) {
if (head == nullptr) {
head = new ListNode{value, nullptr};
} else {
ListNode* newNode = new ListNode{value, head};
head->next = newNode;
head = newNode;
}
size++;
}
// 删除操作(通过值)
bool remove(int value) {
if (size == 0 || head == nullptr)
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;
}
// 查找操作
bool find(int value) const {
ListNode* current = head;
while (current != nullptr) {
if (current->data == value)
return true;
current = current->next;
}
return false;
}
// 修改操作
void update(int oldValue, int newValue) {
if (!find(oldValue))
return; // 如果找不到旧值,则不做任何改变
for (ListNode* current = head; current != nullptr; current = current->next) {
if (current->data == oldValue) {
current->data = newValue;
break;
}
}
}
// 打印列表
void display() const {
ListNode* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
SequenceList list;
list.insert(5);
list.insert(10);
list.insert(15);
list.display(); // 输出: 5 10 15
list.remove(10);
list.update(15, 20);
list.display(); // 输出: 5 20
cout << (list.find(5) ? "Found" : "Not Found") << endl; // 输出: Found
cout << (list.find(10) ? "Found" : "Not Found") << endl; // 输出: Not Found
return 0;
}
```
阅读全文