帮我写一段(递归删除不带头结点单链表中指定值)的代码
时间: 2023-03-12 22:07:18 浏览: 59
void deleteNode(Node* head, int val) {
Node* p = head;
while (p != NULL && p->val != val) {
p = p->next;
} if (p == NULL) return; Node* tmp = p->next;
p->val = tmp->val;
p->next = tmp->next;
delete tmp;
}
相关问题
递归删除不带头结点的单链表中所有值为x的结点
递归删除不带头结点的单链表中所有值为x的结点,可以使用递归的方式实现。具体步骤如下:
1. 如果链表为空,直接返回。
2. 对于非空链表,递归删除其后续部分中值为x的结点。
3. 如果当前结点的值为x,则删除当前结点,即将其后继结点作为当前结点,继续递归删除后续部分中值为x的结点。
4. 如果当前结点的值不为x,则保留当前结点,将其后继结点作为当前结点,继续递归删除后续部分中值为x的结点。
代码实现如下:
```C++
void deleteNode(Node *node, int x) {
if (node == nullptr) { // 链表为空,直接返回
return;
}
if (node->val == x) { // 当前结点的值为x,删除当前结点
Node *temp = node;
node = node->next;
delete temp;
deleteNode(node, x); // 递归删除后续部分中值为x的结点
} else { // 当前结点的值不为x,保留当前结点
deleteNode(node->next, x); // 递归删除后续部分中值为x的结点
}
}
```
其中,`Node` 表示链表结点,包括一个整数值 `val` 和一个指向下一个结点的指针 `next`。使用时,调用 `deleteNode(head, x)` 即可删除不带头结点的单链表 `head` 中所有值为 `x` 的结点。
递归删除不带头结点的单链表L中所有值为x的结点
递归删除不带头结点的单链表L中所有值为x的结点,可以按照以下步骤进行:
1. 如果链表为空,则直接返回;
2. 否则,对于当前链表的第一个结点,如果其值为x,则将其删除,并递归删除剩余部分中所有值为x的结点;
3. 否则,递归删除剩余部分中所有值为x的结点。
具体的删除操作可以使用指针进行实现,代码如下:
```c++
void deleteNode(ListNode*& node, int x) {
if (node == nullptr) {
return;
}
if (node->val == x) {
ListNode* next = node->next;
delete node;
node = next;
deleteNode(node, x);
} else {
deleteNode(node->next, x);
}
}
```
其中,ListNode是单链表的结点类型,其定义如下:
```c++
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
```
在调用上述函数时,需要传入链表的头结点的指针,例如:
```c++
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(2);
deleteNode(head, 2);
```
执行完上述代码后,链表中所有值为2的结点都会被删除。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)