编写一个C++代码整数链表:要求编程实现整数链表类实现以下功能:1链表的创建。2插入结点要能在所有可能的位置上插入结点。3删除节点。4链表遍历输出。5实现结点的查询6注意:考虑用类模板实现通用的链表类。
#include <iostream>
template <class T>
class Node {
public:
T data;
Node<T>* next;
Node(T newData) {
data = newData;
next = nullptr;
}
};
template <class T>
class LinkedList {
private:
Node<T>* head;
public:
LinkedList() {
head = nullptr;
}
// 创建链表
void createList() {
int n;
std::cout << "Enter the number of nodes: ";
std::cin >> n;
if (n <= 0) {
return;
}
std::cout << "Enter the data for each node: ";
for (int i = 0; i < n; i++) {
T newData;
std::cin >> newData;
insertNode(newData);
}
}
// 插入节点
void insertNode(T newData) {
Node<T>* newNode = new Node<T>(newData);
if (head == nullptr) {
head = newNode;
} else {
Node<T>* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 删除节点
void deleteNode(T key) {
if (head == nullptr) {
return;
}
if (head->data == key) {
Node<T>* temp = head;
head = head->next;
delete temp;
} else {
Node<T>* temp = head;
while (temp->next != nullptr && temp->next->data != key) {
temp = temp->next;
}
if (temp->next != nullptr) {
Node<T>* delNode = temp->next;
temp->next = delNode->next;
delete delNode;
}
}
}
// 遍历输出链表
void traverseList() {
Node<T>* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
// 查询节点
bool searchNode(T key) {
Node<T>* temp = head;
while (temp != nullptr) {
if (temp->data == key) {
return true;
}
temp = temp->next;
}
return false;
}
};
int main() {
LinkedList<int> list;
list.createList();
std::cout << "Linked List: ";
list.traverseList();
int choice;
do {
std::cout << "1. Insert Node" << std::endl;
std::cout << "2. Delete Node" << std::endl;
std::cout << "3. Search Node" << std::endl;
std::cout << "4. Traverse List" << std::endl;
std::cout << "5. Exit" << std::endl;
std::cout << "Enter your choice: ";
std::cin >> choice;
switch (choice) {
case 1: {
int newData;
std::cout << "Enter the data to insert: ";
std::cin >> newData;
list.insertNode(newData);
break;
}
case 2: {
int key;
std::cout << "Enter the data to delete: ";
std::cin >> key;
list.deleteNode(key);
break;
}
case 3: {
int key;
std::cout << "Enter the data to search: ";
std::cin >> key;
if (list.searchNode(key)) {
std::cout << "Node found" << std::endl;
} else {
std::cout << "Node not found" << std::endl;
}
break;
}
case 4: {
std::cout << "Linked List: ";
list.traverseList();
break;
}
case 5: {
std::cout << "Exiting..." << std::endl;
break;
}
default: {
std::cout << "Invalid choice" << std::endl;
break;
}
}
} while (choice != 5);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/iJRf 著作权归作者所有。请勿转载和采集!