编写一个程序sqlist.cpp,实现顺序表的各种基本运算和整体建表算法,假设顺序表的元素类型ElemType为char,并在此基础上设计一个主程序
时间: 2024-09-19 16:06:57 浏览: 115
在编写一个名为`sqlist.cpp`的程序来实现顺序表(Sequential List)的各种基本运算和整体建表算法时,我们将首先定义一个顺序表结构体,然后实现插入、删除、搜索、查找长度等操作。在这个例子中,我们假设顺序表的元素类型`ElemType`为`char`。
**1. 定义顺序表结构体(SequentialList.h)**
```cpp
#ifndef SEQUENTIALLIST_H
#define SEQUENTIALLIST_H
#include <iostream>
using namespace std;
// 顺序列表元素类型
typedef char ElemType;
// 顺序表节点结构体
struct Node {
ElemType data;
Node* next; // 指向下一个元素的指针
};
// 顺序表类
class SequentialList {
public:
SequentialList(); // 构造函数
~SequentialList(); // 析构函数
void insert(const char& value); // 插入元素
void remove(const char& value); // 删除元素
bool search(const char& value) const; // 查找元素是否存在
int size() const; // 返回序列长度
private:
Node* head; // 链表头节点
};
#endif // SEQUENTIALLIST_H
```
**2. 实现顺序表操作(SequentialList.cpp)**
```cpp
#include "SequentialList.h"
// 初始化顺序表
SequentialList::SequentialList() : head(nullptr) {}
// 销毁顺序表
SequentialList::~SequentialList() {
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
}
// 插入元素
void SequentialList::insert(const char& value) {
Node* newNode = new Node{value, head};
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next == nullptr) {
current->next = newNode;
}
}
}
// 删除元素
void SequentialList::remove(const char& value) {
if (head == nullptr) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
current->next = current->next->next;
delete current->next;
}
}
// 搜索元素
bool SequentialList::search(const char& value) const {
Node* current = head;
while (current != nullptr) {
if (current->data == value) return true;
current = current->next;
}
return false;
}
// 获取序列长度
int SequentialList::size() const {
int count = 0;
Node* current = head;
while (current != nullptr) {
++count;
current = current->next;
}
return count;
}
```
**3. 主程序示例(main.cpp)**
```cpp
#include <iostream>
#include "SequentialList.h"
int main() {
SequentialList list;
list.insert('A');
list.insert('B');
list.insert('C');
cout << "List Size: " << list.size() << endl;
if (list.search('B')) {
cout << "Found 'B'" << endl;
} else {
cout << "'B' not found" << endl;
}
list.remove('B');
return 0;
}
```
阅读全文