设计一个单向链表类模板,数据从大到小排序,成员函数能进行节点插入删除查找
时间: 2024-03-05 07:48:36 浏览: 69
单向链表类模板_单向链表类模板_fastchq_
好的,以下是一个实现数据从大到小排序的单向链表类模板的设计:
```c++
template<typename T>
class LinkedListNode {
public:
T data; // 存储节点数据
LinkedListNode<T>* next; // 存储指向下一个节点的指针
LinkedListNode(T data) {
this->data = data;
this->next = nullptr;
}
};
template<typename T>
class LinkedList {
private:
LinkedListNode<T>* head; // 存储指向链表头节点的指针
public:
LinkedList() {
this->head = nullptr;
}
~LinkedList() {
LinkedListNode<T>* current = this->head;
while (current != nullptr) {
LinkedListNode<T>* next = current->next;
delete current;
current = next;
}
}
void insert(T data) {
LinkedListNode<T>* node = new LinkedListNode<T>(data);
if (this->head == nullptr) {
this->head = node;
} else if (node->data >= this->head->data) {
node->next = this->head;
this->head = node;
} else {
LinkedListNode<T>* current = this->head;
while (current->next != nullptr && current->next->data >= node->data) {
current = current->next;
}
node->next = current->next;
current->next = node;
}
}
void remove(T data) {
LinkedListNode<T>* current = this->head;
LinkedListNode<T>* previous = nullptr;
while (current != nullptr) {
if (current->data == data) {
if (previous == nullptr) {
this->head = current->next;
} else {
previous->next = current->next;
}
delete current;
return;
}
previous = current;
current = current->next;
}
}
LinkedListNode<T>* find(T data) {
LinkedListNode<T>* current = this->head;
while (current != nullptr) {
if (current->data == data) {
return current;
}
current = current->next;
}
return nullptr;
}
void print() {
LinkedListNode<T>* current = this->head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
```
该链表类具有数据从大到小排序的插入方法、删除节点和查找节点的方法。其中,节点类`LinkedListNode`包含了节点数据和指向下一个节点的指针;链表类`LinkedList`包含了指向链表头节点的指针,以及插入、删除、查找和打印链表的方法。在插入方法中,如果新节点的数据大于等于链表头节点的数据,则插入到链表头部,否则按照从大到小的顺序插入到相应的位置。
阅读全文