请写一段可以实现输入一个整数,在链表中查找这个数,找到第一个后将该节点删除的c++方法
时间: 2024-11-20 08:44:27 浏览: 28
为了在C++中实现这样一个功能,你需要首先创建一个双向链表(因为删除操作通常在双向链表中更容易进行),然后遍历链表,如果找到目标值就删除相应的节点。以下是一个简单的实现:
```cpp
#include <iostream>
using namespace std;
// 定义双向链表节点结构
struct Node {
int data;
Node* prev;
Node* next;
Node(int value) : data(value), prev(nullptr), next(nullptr) {}
};
// 双向链表类
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList() : head(nullptr) {}
// 插入节点
void insertNode(int value) {
if (!head) {
head = new Node(value);
} else {
Node* newNode = new Node(value);
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}
// 查找并删除节点
void deleteFirstOccurrenceOf(int target) {
if (head == nullptr) {
return; // 链表为空,没有元素可删除
}
if (head->data == target) {
Node* temp = head;
head = head->next;
if (head != nullptr) {
head->prev = nullptr;
}
delete temp;
} else {
Node* current = head;
while (current->next != nullptr && current->next->data != target) {
current = current->next;
}
if (current->next != nullptr) { // 找到目标节点
Node* toDelete = current->next;
current->next = toDelete->next;
if (toDelete->next != nullptr) {
toDelete->next->prev = current;
}
delete toDelete;
}
}
}
// 打印链表中的所有节点
void printList() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
DoublyLinkedList list;
list.insertNode(5); // 插入节点5
list.insertNode(7);
list.insertNode(5); // 再次插入节点5
cout << "Original List: ";
list.printList();
list.deleteFirstOccurrenceOf(5); // 删除第一个5
cout << "After deleting the first occurrence of 5: ";
list.printList();
return 0;
}
```
在这个例子中,`deleteFirstOccurrenceOf` 函数会在链表中查找给定的目标值,一旦找到就会删除该节点。注意,这个实现假设链表中的数据都是唯一的;如果存在重复值,可能会误删其他值。
阅读全文
相关推荐


















