从单链表中删除指定的元素x,若x不在单链表中,给出提示信息。x从键盘输入
时间: 2024-02-13 15:03:16 浏览: 33
好的,这是一个比较基础的链表操作,我可以为您提供一份 C++ 的代码示例:
```c++
#include <iostream>
using namespace std;
// 链表结点的结构体定义
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 删除链表中指定元素的函数
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr) return nullptr; // 特判空链表
while (head->val == val) { // 头结点需要被删除
head = head->next;
if (head == nullptr) return nullptr; // 特判空链表
}
ListNode* p = head;
while (p->next != nullptr) { // 遍历链表
if (p->next->val == val) {
p->next = p->next->next; // 删除结点
} else {
p = p->next; // 继续遍历
}
}
return head;
}
int main() {
// 构造链表 1->2->6->3->4->5->6
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(6);
head->next->next->next = new ListNode(3);
head->next->next->next->next = new ListNode(4);
head->next->next->next->next->next = new ListNode(5);
head->next->next->next->next->next->next = new ListNode(6);
// 删除元素 6
head = removeElements(head, 6);
// 输出链表
ListNode* p = head;
while (p != nullptr) {
cout << p->val << " -> ";
p = p->next;
}
cout << "nullptr" << endl;
return 0;
}
```
您可以将这段代码复制到本地的 C++ 开发环境中进行编译运行,其中的 `removeElements` 函数就是删除链表中指定元素的实现。需要注意的是,这个函数返回的是删除指定元素后的链表头结点指针,如果链表为空或指定元素不在链表中,则返回 `nullptr`。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)