下面是一个简单的单向链表实现,包括了增加、删除、修改和查找节点的基本操作函数。请注意,这里只是一个基础实现,并没有进行复杂的错误检查和异常处理。
#include <iostream>
// 定义链表节点结构体
struct Node {
int data; // 数据域
Node* next; // 指针域,指向下一个节点
Node(int val) : data(val), next(NULL) {} // 构造函数
};
// 链表类
class LinkedList {
public:
LinkedList() : head(NULL) {} // 构造函数
void append(int value);
void deleteNode(int value);
void update(int oldValue, int newValue);
bool find(int value);
void printList();
private:
Node* head; // 链表头指针
};
// 类成员函数的实现
void LinkedList::append(int value) {
Node* newNode = new Node(value);
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void LinkedList::deleteNode(int value) {
if (head == NULL) return;
Node* temp = head;
if (temp->data == value) {
head = temp->next;
delete temp;
return;
}
Node* prev = NULL;
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
delete temp;
}
void LinkedList::update(int oldValue, int newValue) {
Node* current = head;
while (current != NULL) {
if (current->data == oldValue) {
current->data = newValue;
return;
}
current = current->next;
}
}
bool LinkedList::find(int value) {
Node* current = head;
while (current != NULL) {
if (current->data == value) {
return true;
}
current = current->next;
}
return false;
}
void LinkedList::printList() {
Node* current = head;
while (current != NULL) {
std::cout << current->data << " -> ";
current = current->next;
}
std::cout << "null" << std::endl;
}
int main() {
LinkedList list;
list.append(1);
list.append(2);
list.append(3);
list.append(4);
std::cout << "Initial list: ";
list.printList();
list.deleteNode(2);
std::cout << "After deleting 2: ";
list.printList();
list.update(3, 30);
std::cout << "After updating 3 to 30: ";
list.printList();
if (list.find(30)) {
std::cout << "30 is found in the list." << std::endl;
} else {
std::cout << "30 is not found in the list." << std::endl;
}
return 0;
}
这个程序定义了一个链表类LinkedList,它包含了增加节点到尾部、删除节点、更新节点数据和查找节点数据的功能。在main函数中,我们创建了一个链表实例,对其进行了几个基本操作,并打印了操作后的链表状态。
1250

被折叠的 条评论
为什么被折叠?



