C++ 整数链表实现:创建、插入、删除、遍历、查询
#include
template
Node(T value) {
data = value;
next = nullptr;
}
};
template
public: LinkedList() { head = nullptr; }
void insertNode(T value) {
Node<T>* newNode = new Node<T>(value);
if (head == nullptr) {
head = newNode;
} else {
Node<T>* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
void deleteNode(T value) {
if (head == nullptr) {
return;
}
if (head->data == value) {
Node<T>* temp = head;
head = head->next;
delete temp;
return;
}
Node<T>* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node<T>* temp = current->next;
current->next = current->next->next;
delete temp;
}
}
void printList() {
Node<T>* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
bool searchNode(T value) {
Node<T>* current = head;
while (current != nullptr) {
if (current->data == value) {
return true;
}
current = current->next;
}
return false;
}
};
int main() {
LinkedList
list.insertNode(1);
list.insertNode(2);
list.insertNode(3);
list.insertNode(4);
list.insertNode(5);
list.printList();
list.deleteNode(3);
list.printList();
std::cout << "Search 4: " << (list.searchNode(4) ? "Found" : "Not found") << std::endl;
std::cout << "Search 6: " << (list.searchNode(6) ? "Found" : "Not found") << std::endl;
return 0;
} 该示例代码使用类模板实现了一个通用的整数链表类。它具有创建链表、插入结点、删除结点、遍历输出链表和查询结点的功能。
在main函数中,我们首先创建一个LinkedList<int>对象,并通过insertNode方法插入了一些整数结点。然后,我们使用printList方法输出链表的内容。
接下来,我们使用deleteNode方法删除值为3的结点,并再次使用printList方法输出链表内容。
最后,我们使用searchNode方法查询值为4和6的结点是否存在,并输出结果。
注意:示例代码中的链表实现使用了动态内存分配,因此需要在适当的时候使用delete操作符释放内存,以避免内存泄漏。
原文地址: https://www.cveoy.top/t/topic/qgX6 著作权归作者所有。请勿转载和采集!