建立顺序表,完成顺序表的基本操作:初始化、插入、删除、逆转、输出、销毁,置空表、求表长、查找元素、判线性表是否为空;写出代码
时间: 2024-11-12 09:33:08 浏览: 13
在许多编程语言中,我们可以创建简单的顺序表数据结构来存储一系列元素。这里我将以C++为例,给出基本操作的实现:
```cpp
#include <iostream>
using namespace std;
// 定义节点结构体
struct Node {
int data; // 数据域
Node* next; // 指针域,指向下一个节点
};
// 顺序表类
class LinkedList {
private:
Node* head; // 链表头指针,表示链表是否为空
public:
// 初始化链表为空
LinkedList() : head(nullptr) {}
// 插入元素到链表末尾
void insert(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 删除指定值的节点(如果存在)
void remove(int value) {
if (head == nullptr) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* prev = head;
Node* curr = head->next;
while (curr != nullptr && curr->data != value) {
prev = curr;
curr = curr->next;
}
if (curr == nullptr) return; // 未找到
prev->next = curr->next;
delete curr;
}
// 反转链表
void reverse() {
Node* prev = nullptr, *current = head, *next = nullptr;
while (current != nullptr) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
// 输出链表
void printList() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// 置空表
void clear() {
Node* temp = head;
while (temp != nullptr) {
Node* oldHead = temp;
temp = temp->next;
delete oldHead;
}
head = nullptr;
}
// 获取链表长度(表长)
int size() const {
int count = 0;
Node* temp = head;
while (temp != nullptr) {
count++;
temp = temp->next;
}
return count;
}
// 查找元素
bool search(int value) const {
Node* temp = head;
while (temp != nullptr) {
if (temp->data == value) return true;
temp = temp->next;
}
return false;
}
// 判断线性表是否为空
bool isEmpty() const {
return head == nullptr;
}
~LinkedList() { // 析构函数,释放内存
clear();
}
};
int main() {
LinkedList list;
// 使用list对象进行操作...
return 0;
}
```
阅读全文