删除单链表中与输入值相等的数据元素,写出c++完整代码
时间: 2024-10-04 17:03:05 浏览: 41
在C++中,删除单链表中所有等于给定值的节点可以使用迭代或者递归的方式实现。这里是一个使用迭代方法的示例代码:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 删除链表中等于给定值的节点
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr) return nullptr; // 如果链表为空,直接返回
ListNode* dummy = new ListNode(0); // 创建一个虚拟头结点
dummy->next = head;
ListNode* prev = dummy;
ListNode* curr = head;
while (curr != nullptr) {
if (curr->val == val) {
prev->next = curr->next;
delete curr; // 删除当前节点
} else {
prev = curr; // 更新前驱指针
}
curr = curr->next;
}
return dummy->next; // 返回实际的链表头结点
}
// 测试函数
void printList(ListNode* head) {
while (head) {
cout << head->val << " -> ";
head = head->next;
}
cout << "nullptr" << endl;
}
int main() {
// 创建一个测试链表
ListNode* list = new ListNode(1);
list->next = new ListNode(2);
list->next->next = new ListNode(3);
list->next->next->next = new ListNode(2);
list->next->next->next->next = new ListNode(4);
int valToRemove = 2;
cout << "Original List: ";
printList(list);
list = removeElements(list, valToRemove);
cout << "List after removing elements with value " << valToRemove << ": ";
printList(list);
return 0;
}
```
这个代码首先创建了一个简单的单链表,然后通过`removeElements`函数删除所有值为`valToRemove`的节点,并返回新的链表头结点。最后打印处理后的链表。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)