c++编写有序顺序表类
时间: 2024-09-17 17:09:40 浏览: 90
在C++中,你可以创建一个名为`OrderedList`的有序顺序表类,通常使用数组或链表作为底层数据结构来存储元素,并通过排序算法保证其有序性。这里是一个简单的例子,我们使用冒泡排序作为内部排序算法:
```cpp
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
class OrderedList {
private:
Node* head; // 链表头指针
int size; // 列表长度
// 冒泡排序函数用于内部排序
void bubbleSort(Node* start);
public:
// 构造函数
OrderedList() : head(nullptr), size(0) {}
// 插入元素并保持有序
void insert(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->next->data < value) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
size++;
}
// 打印列表
void print() {
if (head == nullptr) {
cout << "List is empty." << endl;
return;
}
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// 释放内存
~OrderedList() {
clearList();
}
private:
// 清空列表并删除所有节点
void clearList() {
Node* temp = head;
while (temp != nullptr) {
Node* nextTemp = temp->next;
delete temp;
temp = nextTemp;
}
head = nullptr;
size = 0;
}
};
// 实现冒泡排序
void OrderedList::bubbleSort(Node* start) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (start->next->data > start->data) {
swap(start->data, start->next->data);
}
start = start->next;
}
}
}
int main() {
OrderedList list;
list.insert(5);
list.insert(2);
list.insert(8);
list.insert(1);
list.print(); // 输出: 1 2 5 8
return 0;
}
```
阅读全文